import { Check, ChevronDown } from 'lucide-react';
import { useLocale, useMessages } from '@/i18n/client';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import { AURA_COLOR_NAMES, readAuraField } from '@/lib/aura/auraField';
import { CHAKRA_DETAIL, CHAKRA_PLAIN, CHAKRA_READING, chakraLevel, type ChakraLevel } from '@/lib/aura/chakraGuide';
import { AURA_SIZE_BANDS, CHAKRA_SHAPES, auraSize, chakraShape, pickAuraType, sizeBand } from '@/lib/aura/auraReport';
import { AURA_PERSONALITY } from '@/lib/aura/personality';
import { PERSONALITY_SECTIONS } from '@/lib/aura/personalitySections';
import { GRAPH_TEXT, auraWave, mindBodySpirit, relaxationLevel, yinYang } from '@/lib/aura/energyGraphs';
import { auraScript } from '@/lib/aura/auraScript';
import type { ChakraType } from '@/lib/aura/types';
import { AuraColorGuide, AuraPhoto, AuraZoneLegend } from '@/components/insights/AuraPhoto';
import { AuraBodyMap } from '@/components/insights/AuraBodyMap';
import { AuraSizeRings, AuraTypeSpectrum, ChakraShapeIcon, ChakraShapeLegend } from '@/components/insights/AuraChakraReport';
import {
  AuraWave,
  ChakraBarGraph3D,
  MBS_COLOR,
  MindBodySpiritPie,
  RelaxationBars,
  YinYangWheel,
  type MbsPart,
} from '@/components/insights/AuraGraphs';
import { cn } from '@/lib/cn';
import { BulletList, Card, CardTitle, Chapter, Prose, type AuraChapterProps } from './ReportChapters';

const BOTTOM_UP: ChakraType[] = ['root', 'sacral', 'solar_plexus', 'heart', 'throat', 'third_eye', 'crown'];

const LEVEL_STYLE: Record<ChakraLevel, string> = {
  high: 'bg-wood/10 text-wood',
  mid: 'bg-earth/10 text-earth',
  low: 'bg-fire/10 text-fire',
};

function useZones(profile: AuraChapterProps['profile']) {
  const locale = useLocale();
  const { aura } = profile;
  return readAuraField(aura.normalizedScores, { dominant: aura.dominantChakra, secondary: aura.secondaryChakra }, locale);
}

/* ------------------------------------------------------------------ */

export function AuraPhotoChapter({ profile, onAsk }: AuraChapterProps) {
  const locale = useLocale();
  const all = useMessages();
  const t = all.auraReport.photo;
  const zones = useZones(profile);
  const dominant = chakraMeta(locale)[profile.aura.dominantChakra];

  return (
    <Chapter
      id="foto-aura"
      title={all.report.view.chapters['foto-aura']}
      lead={t.lead(dominant.archetype, profile.aura.overallEnergyScore)}
      onAsk={onAsk && (() => onAsk(t.ask))}
    >
      <div className="relative overflow-hidden rounded-panel bg-night-950 p-5 sm:p-10 print:bg-night-900">
        <div
          aria-hidden
          className="absolute inset-0 opacity-50 blur-3xl"
          style={{
            background: `radial-gradient(60% 50% at 30% 40%, ${zones.find((z) => z.zone === 'center')!.color}55, transparent 70%)`,
          }}
        />
        <div className="relative grid items-center gap-8 md:grid-cols-[minmax(0,5fr)_minmax(0,6fr)] md:gap-12">
          {profile.photo ? (
            <AuraPhoto photo={profile.photo} zones={zones} className="mx-auto w-full max-w-sm -rotate-1" />
          ) : (
            <div>
              <AuraBodyMap scores={profile.aura.normalizedScores} zones={zones} />
              <p className="mt-3 text-center text-xs text-white/45">{t.noPhoto}</p>
            </div>
          )}
          <div className="text-white">
            <p className="eyebrow text-white/50">{t.zonesTitle}</p>
            <h3 className="mt-2 text-2xl font-semibold tracking-tight">{t.title}</h3>
            <p className="mt-3 text-sm leading-relaxed text-white/65">{t.text}</p>
            <div className="mt-6 rounded-card bg-white p-4 sm:p-5">
              <AuraZoneLegend zones={zones} />
            </div>
          </div>
        </div>
      </div>

      <Card>
        <CardTitle>{t.colorsTitle}</CardTitle>
        <AuraColorGuide zones={zones} className="mt-5" />
      </Card>
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */

export function AuraBodyChapter({ profile, onAsk }: AuraChapterProps) {
  const locale = useLocale();
  const all = useMessages();
  const t = all.auraReport.body;
  const zones = useZones(profile);
  const meta = chakraMeta(locale);
  const dominant = meta[profile.aura.dominantChakra];
  const growth = meta[profile.aura.growthChakra];

  return (
    <Chapter id="aura-tubuh" title={all.report.view.chapters['aura-tubuh']} lead={t.lead} onAsk={onAsk && (() => onAsk(t.ask))}>
      <div className="rounded-panel bg-night-950 p-4 sm:p-8 print:bg-night-900">
        <AuraBodyMap scores={profile.aura.normalizedScores} zones={zones} className="mx-auto max-w-2xl" />
        <p className="mx-auto mt-6 max-w-2xl text-center text-sm leading-relaxed text-white/60">{t.text}</p>
      </div>
      <div className="grid gap-4 md:grid-cols-2">
        {[
          { c: dominant, label: t.dominant, text: t.dominantText(dominant.theme) },
          { c: growth, label: t.growth, text: t.growthText(growth.theme) },
        ].map(({ c, label, text }) => (
          <Card key={label}>
            <p className="eyebrow" style={{ color: c.color }}>
              {label}
            </p>
            <h3 className="mt-3 flex items-center gap-2.5 text-lg font-semibold text-ink">
              <span aria-hidden className="size-3.5 rounded-full" style={{ backgroundColor: c.color, boxShadow: `0 0 12px ${c.color}` }} />
              {c.name} <span className="font-normal text-subtle">· {c.sanskrit}</span>
            </h3>
            <Prose>{text}</Prose>
          </Card>
        ))}
      </div>
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */

// Floored so the 1–10 value always agrees with the level bands (≥70 high, ≥45 mid).
const toTen = (score: number) => Math.max(1, Math.min(10, Math.floor(score / 10)));

export function ChakraGraphChapter({ profile, onAsk }: AuraChapterProps) {
  const locale = useLocale();
  const all = useMessages();
  const t = all.auraReport.graph;
  const g = all.report.guide;
  const meta = chakraMeta(locale);
  const scores = profile.aura.normalizedScores;
  const shapes = CHAKRA_SHAPES[locale];

  return (
    <Chapter id="grafik-cakra" title={all.report.view.chapters['grafik-cakra']} lead={t.lead} onAsk={onAsk && (() => onAsk(t.ask))}>
      <div className="rounded-panel bg-[radial-gradient(120%_90%_at_25%_30%,#1A2350,#0A1024_60%,#070B19)] p-4 sm:p-8 print:bg-night-900">
        <p className="eyebrow text-white/45">{t.scale}</p>
        <ChakraBarGraph3D
          className="mt-3"
          points={BOTTOM_UP.map((key) => ({ key, label: meta[key].short, value: toTen(scores[key]), color: meta[key].color }))}
        />
      </div>
      <Card className="bg-canvas shadow-none">
        <Prose>{t.text}</Prose>
      </Card>

      <div>
        <h3 className="text-lg font-semibold text-ink">{t.detailTitle}</h3>
        <p className="mt-1 text-sm text-muted">{t.detailText}</p>
      </div>
      <ol className="space-y-3">
        {BOTTOM_UP.map((key, i) => {
          const c = meta[key];
          const detail = CHAKRA_DETAIL[locale][key];
          const score = scores[key];
          const lv = chakraLevel(score);
          const shape = chakraShape(score);
          return (
            <li key={key} className="overflow-hidden rounded-card bg-surface shadow-card ring-1 ring-line/70">
              <div className="h-1" style={{ background: c.color }} aria-hidden />
              <div className="grid gap-5 p-5 sm:grid-cols-[150px_minmax(0,1fr)] sm:p-6">
                <div className="flex items-center gap-4 sm:flex-col sm:items-start">
                  <ChakraShapeIcon shape={shape} color={c.color} className="size-14 shrink-0" />
                  <div>
                    <p className="text-[11px] font-medium text-subtle">
                      {i + 1} · {c.sanskrit}
                    </p>
                    <p className="text-[15px] font-semibold text-ink">{c.name}</p>
                    <p className="mt-1 text-xs text-muted">
                      {t.activity} <span className="font-semibold text-ink tabular-nums">{toTen(score)}/10</span>
                    </p>
                    <p className="text-xs text-muted">
                      {t.shape} <span className="font-medium text-ink">{shapes[shape].label}</span>
                    </p>
                  </div>
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted">{CHAKRA_PLAIN[locale][key]}</p>
                  <ul className="mt-3 space-y-2">
                    {(['high', 'mid', 'low'] as ChakraLevel[]).map((l) => {
                      const on = l === lv;
                      return (
                        <li
                          key={l}
                          className={cn(
                            'flex gap-3 rounded-xl px-3 py-2.5 text-[13px] leading-relaxed',
                            on ? 'bg-canvas text-ink ring-1 ring-line' : 'text-subtle',
                          )}
                        >
                          <span
                            className={cn(
                              'mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-[5px] ring-1',
                              on ? 'text-white ring-transparent' : 'ring-line',
                            )}
                            style={on ? { backgroundColor: c.color } : undefined}
                          >
                            {on && <Check className="size-3" strokeWidth={3} aria-hidden />}
                          </span>
                          <p>
                            <span className={cn('mr-1.5 rounded-full px-2 py-0.5 text-[11px] font-medium', on ? LEVEL_STYLE[l] : 'bg-canvas')}>
                              {t.levels[l]}
                            </span>
                            {CHAKRA_READING[locale][key][l]}
                          </p>
                        </li>
                      );
                    })}
                  </ul>
                  <details className="group mt-3">
                    <summary className="inline-flex cursor-pointer list-none items-center gap-1 text-[13px] font-medium text-accent [&::-webkit-details-marker]:hidden">
                      {g.practices}
                      <ChevronDown className="size-3.5 transition-transform group-open:rotate-180" aria-hidden />
                    </summary>
                    <div className="mt-4 space-y-4">
                      <dl className="grid grid-cols-3 gap-px overflow-hidden rounded-xl bg-line text-xs ring-1 ring-line">
                        {[
                          [g.location, c.location],
                          [g.color, AURA_COLOR_NAMES[locale][key]],
                          [g.element, detail.element],
                        ].map(([k, v]) => (
                          <div key={k} className="bg-surface p-3">
                            <dt className="text-subtle">{k}</dt>
                            <dd className="mt-0.5 font-medium text-ink">{v}</dd>
                          </div>
                        ))}
                      </dl>
                      <p className="text-sm leading-relaxed text-ink-soft">{detail.about}</p>
                      <div className="grid gap-5 sm:grid-cols-2">
                        <div>
                          <p className="text-xs font-semibold text-wood">{g.balanced}</p>
                          <BulletList items={detail.balanced} />
                        </div>
                        <div>
                          <p className="text-xs font-semibold text-fire">{g.imbalanced}</p>
                          <BulletList items={detail.imbalanced} />
                        </div>
                      </div>
                      <div>
                        <p className="text-xs font-semibold text-ink">{g.practices}</p>
                        <BulletList items={detail.practices} />
                      </div>
                      <p
                        className="rounded-xl px-4 py-3 text-sm leading-relaxed text-ink italic"
                        style={{ backgroundColor: `${c.color}14`, borderLeft: `3px solid ${c.color}` }}
                      >
                        “{detail.affirmation}”
                      </p>
                    </div>
                  </details>
                </div>
              </div>
            </li>
          );
        })}
      </ol>

      <Card>
        <CardTitle>{t.shapesTitle}</CardTitle>
        <div className="mt-4">
          <ChakraShapeLegend />
        </div>
      </Card>
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */

export function EnergyGraphsChapter({ profile, onAsk }: AuraChapterProps) {
  const locale = useLocale();
  const all = useMessages();
  const t = all.auraReport.energy;
  const gt = GRAPH_TEXT[locale];
  const meta = chakraMeta(locale);
  const scores = profile.aura.normalizedScores;
  const zones = useZones(profile);

  const mbs = mindBodySpirit(scores);
  const parts: MbsPart[] = ['mind', 'body', 'spirit'];
  const leadPart = parts.reduce((a, b) => (mbs[b] > mbs[a] ? b : a));
  const power = auraSize(scores);
  const pBand = sizeBand(power);
  const powerBands = AURA_SIZE_BANDS[locale];
  const wave = auraWave(scores);
  const yy = yinYang(zones);
  const relax = relaxationLevel(scores);
  const colors = Object.fromEntries(BOTTOM_UP.map((k) => [k, meta[k].color])) as Record<ChakraType, string>;

  return (
    <Chapter id="grafik-energi" title={all.report.view.chapters['grafik-energi']} lead={t.lead} onAsk={onAsk && (() => onAsk(t.ask))}>
      {/* Mind · Body · Spirit */}
      <Card>
        <CardTitle>{gt.mbs.title}</CardTitle>
        <Prose>{gt.mbs.text}</Prose>
        <div className="mt-5 grid items-center gap-6 sm:grid-cols-[220px_minmax(0,1fr)]">
          <MindBodySpiritPie
            values={mbs}
            labels={{ mind: gt.mbs.mind, body: gt.mbs.body, spirit: gt.mbs.spirit }}
            className="mx-auto w-full max-w-[220px]"
          />
          <ul className="space-y-3">
            {parts.map((p) => (
              <li key={p} className={cn('rounded-xl p-3 text-[13px] leading-relaxed', p === leadPart ? 'bg-canvas ring-1 ring-line' : '')}>
                <p className="flex items-center gap-2 font-semibold text-ink">
                  <span aria-hidden className="size-2.5 rounded-full" style={{ backgroundColor: MBS_COLOR[p] }} />
                  {gt.mbs[p]} <span className="font-normal text-subtle tabular-nums">· {mbs[p]}%</span>
                </p>
                <p className="mt-0.5 text-ink-soft">{gt.mbs[`${p}Text`]}</p>
              </li>
            ))}
          </ul>
        </div>
        <p className="mt-4 text-sm font-medium text-ink">{gt.mbs.lead(gt.mbs[leadPart])}</p>
      </Card>

      <div className="grid gap-4 md:grid-cols-2">
        {/* Aura power */}
        <Card>
          <CardTitle>{gt.power.title}</CardTitle>
          <Prose>{gt.power.text}</Prose>
          <AuraSizeRings value={power} className="mx-auto mt-4 size-48" />
          <p className="mt-3 text-[11px] font-medium text-subtle uppercase">{t.powerBands}</p>
          <ul className="mt-2 space-y-1.5">
            {(['high', 'mid', 'low'] as const).map((b) => (
              <li key={b} className={cn('flex gap-2 text-[13px] leading-snug', b === pBand ? 'text-ink' : 'text-subtle')}>
                <Check className={cn('mt-0.5 size-4 shrink-0', b === pBand ? 'text-wood' : 'invisible')} aria-hidden />
                <p>
                  <span className="font-semibold">
                    {powerBands[b].label} ({powerBands[b].range})
                  </span>
                  {b === pBand && <span className="text-ink-soft">. {powerBands[b].text}</span>}
                </p>
              </li>
            ))}
          </ul>
        </Card>

        {/* Relaxation */}
        <Card>
          <CardTitle>{gt.relax.title}</CardTitle>
          <Prose>{gt.relax.text}</Prose>
          <RelaxationBars level={relax} low={gt.relax.low} high={gt.relax.high} className="mt-6" />
          <p className="mt-4 text-2xl font-semibold text-ink tabular-nums">{gt.relax.level(relax)}</p>
          <p className="mt-1 text-sm leading-relaxed text-ink-soft">{gt.relax.read(relax)}</p>
        </Card>
      </div>

      {/* Aura wave */}
      <Card>
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <CardTitle>{gt.wave.title}</CardTitle>
            <Prose>{gt.wave.text}</Prose>
          </div>
          <span
            className={cn(
              'rounded-full px-3 py-1 text-xs font-medium',
              wave.band === 'calm' ? LEVEL_STYLE.high : wave.band === 'mixed' ? LEVEL_STYLE.mid : LEVEL_STYLE.low,
            )}
          >
            {gt.wave.labels[wave.band]} · {t.balance(wave.balance)}
          </span>
        </div>
        <div className="mt-5 rounded-2xl bg-canvas px-2 py-3 text-ink">
          <AuraWave amplitude={wave.amplitude} colors={BOTTOM_UP.map((k) => meta[k].color)} />
        </div>
        <p className="mt-4 text-sm leading-relaxed text-ink-soft">{gt.wave.bands[wave.band]}</p>
      </Card>

      {/* Yin-yang wheel */}
      <Card>
        <CardTitle>{gt.wheel.title}</CardTitle>
        <Prose>{gt.wheel.text}</Prose>
        <div className="mt-5 grid items-center gap-6 sm:grid-cols-[240px_minmax(0,1fr)]">
          <YinYangWheel colors={colors} yin={yy.yin.chakra} yang={yy.yang.chakra} className="mx-auto w-full max-w-[240px]" />
          <div className="space-y-3">
            <p className="text-sm leading-relaxed text-ink-soft">{gt.wheel.yinYangText}</p>
            <dl className="grid grid-cols-2 gap-3">
              {[
                { label: gt.wheel.yin, z: yy.yin, sign: '♀', color: '#EC4899' },
                { label: gt.wheel.yang, z: yy.yang, sign: '♂', color: '#2563EB' },
              ].map(({ label, z, sign, color }) => (
                <div key={label} className="rounded-xl bg-canvas p-3">
                  <dt className="text-[11px] font-medium text-subtle">
                    <span style={{ color }}>{sign}</span> {label}
                  </dt>
                  <dd className="mt-1 flex items-center gap-2 text-sm font-semibold text-ink">
                    <span aria-hidden className="size-3 rounded-full" style={{ backgroundColor: z.color }} />
                    {z.colorName}
                  </dd>
                </div>
              ))}
            </dl>
            <p
              className={cn(
                'rounded-xl px-3 py-2.5 text-[13px] leading-relaxed',
                yy.harmonious ? 'bg-wood/10 text-ink' : 'bg-earth/10 text-ink',
              )}
            >
              {yy.harmonious ? gt.wheel.harmonious : gt.wheel.imbalanced}
            </p>
          </div>
        </div>
      </Card>

      <p className="text-xs leading-relaxed text-subtle">{t.note}</p>
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */

export function AuraScriptChapter({ profile, onAsk }: AuraChapterProps) {
  const locale = useLocale();
  const all = useMessages();
  const t = all.auraReport.script;
  const zones = useZones(profile);
  const entries = auraScript(zones, locale);
  const obs = profile.scan.observations;

  return (
    <Chapter id="warna-zona" title={all.report.view.chapters['warna-zona']} lead={t.lead} onAsk={onAsk && (() => onAsk(t.ask))}>
      <Card className="bg-canvas shadow-none">
        <Prose>{t.text}</Prose>
      </Card>
      <ol className="space-y-3">
        {entries.map((e) => (
          <li key={e.zone} className="relative overflow-hidden rounded-card bg-surface p-5 pl-7 shadow-card ring-1 ring-line/70 sm:p-6 sm:pl-8">
            <span aria-hidden className="absolute inset-y-0 left-0 w-1.5" style={{ background: e.color }} />
            <h3 className="flex items-center gap-3 text-[15px] font-semibold text-ink">
              <span
                aria-hidden
                className="size-7 shrink-0 rounded-full"
                style={{ background: `radial-gradient(circle at 35% 35%, #fff8, ${e.color} 60%)`, boxShadow: `0 0 14px ${e.color}88` }}
              />
              {e.title}
            </h3>
            <p className="mt-2.5 text-sm leading-relaxed text-ink-soft">{e.body}</p>
          </li>
        ))}
      </ol>

      {obs && (
        <Card>
          <CardTitle>{t.readingTitle}</CardTitle>
          <dl className="mt-4 grid gap-x-8 gap-y-5 sm:grid-cols-2">
            {[
              [t.reading.focus, obs.eyeClarity],
              [t.reading.vitality, obs.vitalityTone],
              [t.reading.harmony, obs.expressionHarmony],
              [t.reading.spectrum, obs.auricColorSpectrum],
            ].map(([k, v]) => (
              <div key={k}>
                <dt className="text-xs font-medium text-subtle">{k}</dt>
                <dd className="mt-1 text-sm leading-relaxed text-ink-soft">{v}</dd>
              </div>
            ))}
          </dl>
        </Card>
      )}
    </Chapter>
  );
}

/* ------------------------------------------------------------------ */

export function ColorPersonalityChapter({ profile, onAsk }: AuraChapterProps) {
  const locale = useLocale();
  const all = useMessages();
  const t = all.auraReport.personality;
  const type = pickAuraType(profile.aura, locale);
  const persona = AURA_PERSONALITY[locale][type.base];
  const sections = PERSONALITY_SECTIONS[locale][type.base];
  const accent = type.id === 'putih' ? '#A8A29E' : type.color;

  return (
    <Chapter
      id="kepribadian"
      title={all.report.view.chapters.kepribadian}
      lead={t.lead(type.name)}
      onAsk={onAsk && (() => onAsk(t.ask(type.name)))}
    >
      <div className="relative overflow-hidden rounded-panel p-6 text-white sm:p-10" style={{ background: `linear-gradient(135deg, ${type.color}, #0B1020 85%)` }}>
        <div aria-hidden className="absolute -top-20 -right-16 size-72 rounded-full bg-white/10 blur-3xl" />
        <p className="eyebrow relative text-white/60">{t.typeEyebrow}</p>
        <h3 className="relative mt-3 text-[34px] leading-tight font-semibold tracking-[-0.02em]">{type.name}</h3>
        <p className="relative mt-3 max-w-xl text-[15px] leading-relaxed text-white/80">{type.traits}</p>
      </div>

      <div className="grid gap-4 lg:grid-cols-[minmax(0,5fr)_minmax(0,6fr)]">
        <Card>
          <CardTitle>{t.spectrumTitle}</CardTitle>
          <div className="mt-5">
            <AuraTypeSpectrum active={type} />
          </div>
        </Card>
        <Card>
          <p className="eyebrow" style={{ color: accent }}>
            {persona.name}
          </p>
          <h3 className="mt-2 text-lg font-semibold text-ink">{t.tableTitle(persona.name)}</h3>
          <dl className="mt-4 divide-y divide-line">
            {persona.areas.map(([area, desc]) => (
              <div key={area} className="grid gap-1 py-2.5 sm:grid-cols-[130px_minmax(0,1fr)] sm:gap-5">
                <dt className="text-[13px] font-medium text-subtle italic">{area}</dt>
                <dd className="text-[13px] leading-relaxed text-ink-soft">{desc}</dd>
              </div>
            ))}
          </dl>
        </Card>
      </div>

      <Card>
        <CardTitle>{t.mindBody}</CardTitle>
        <div className="mt-3 space-y-3">
          {persona.narrative.map((para) => (
            <p key={para.slice(0, 24)} className="text-sm leading-relaxed text-ink-soft">
              {para}
            </p>
          ))}
        </div>
        <p className="mt-5 rounded-xl px-4 py-3 text-sm leading-relaxed text-ink" style={{ backgroundColor: `${accent}14`, borderLeft: `3px solid ${accent}` }}>
          {persona.inBalance}
        </p>
      </Card>

      <div className="grid gap-4 md:grid-cols-2">
        {(['social', 'relationships', 'career', 'wellness'] as const).map((k) => (
          <Card key={k}>
            <p className="eyebrow" style={{ color: accent }}>
              {persona.name}
            </p>
            <h3 className="mt-2 text-[15px] font-semibold text-ink">{t[k]}</h3>
            <div className="mt-2 space-y-2.5">
              {sections[k].map((para) => (
                <p key={para.slice(0, 24)} className="text-sm leading-relaxed text-ink-soft">
                  {para}
                </p>
              ))}
            </div>
          </Card>
        ))}
      </div>
    </Chapter>
  );
}
