/* Brand Lens — the living photography style guide (built from your real calls) */
function StyleGuide({ recs, goReview }) {
  const reviewed = useMemo(() => recs.filter((r) => r.user && r.ai), [recs]);
  const liked = useMemo(() => recs.filter((r) => r.user && r.user.like).sort((a, b) => (b.ai ? b.ai.score : 0) - (a.ai ? a.ai.score : 0)), [recs]);
  const disliked = useMemo(() => recs.filter((r) => r.user && !r.user.like), [recs]);

  const [guide, setGuide] = useState(() => {
    try { return JSON.parse(localStorage.getItem('lens-guide') || 'null'); } catch (e) { return null; }
  });
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);

  async function build() {
    setBusy(true); setErr(null);
    try {
      const g = await window.Lens.generateGuide(recs);
      setGuide(g);
      localStorage.setItem('lens-guide', JSON.stringify(g));
    } catch (e) { setErr(e.message || 'Generation failed'); }
    setBusy(false);
  }

  if (reviewed.length < 3) {
    return <window.LensEmpty title="Review a few more first"
      body={`The style guide learns from your calls and comments. Review at least 3 images (you've done ${reviewed.length}) and it'll have enough signal to synthesize.`}
      cta="Continue blind review" onCta={goReview} />;
  }

  const stale = guide && guide.basedOn !== reviewed.length;

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ps-primary-blue)', marginBottom: 12 }}>Proper Sky · Photography</div>
          <h2 style={{ fontSize: 'clamp(26px,2.8vw,34px)', margin: 0, fontWeight: 500, letterSpacing: '-.015em' }}>Your living style guide</h2>
        </div>
        <Btn kind={guide ? 'ghost' : 'primary'} icon={busy ? null : 'sparkle'} onClick={build} disabled={busy}>
          {busy ? <><Spinner size={15} /> Synthesizing…</> : guide ? 'Refresh from latest' : 'Generate style guide'}
        </Btn>
      </div>
      <p style={{ fontSize: 16, color: 'var(--fg-2)', margin: '12px 0 0', maxWidth: '64ch', lineHeight: 1.6 }}>
        Distilled from your {reviewed.length} reviewed images and your own comments. Generating or refreshing it <strong style={{ color: 'var(--fg-1)', fontWeight: 500 }}>re-teaches the judge</strong> — your next Calibrate round will score with this folded in, so agreement climbs over rounds.
      </p>

      {err && <div style={{ marginTop: 18, padding: '12px 16px', background: 'var(--ps-flag-soft)', color: 'var(--ps-flag-ink)', borderRadius: 10, fontSize: 14 }}>{err}</div>}

      {!guide && !busy && (
        <div style={{ marginTop: 26, padding: '40px 30px', textAlign: 'center', border: '2px dashed var(--ps-line-strong)', borderRadius: 18, background: 'var(--ps-cloud-gray)' }}>
          <Icon name="sparkle" size={34} style={{ color: 'var(--ps-primary-blue)' }} />
          <div style={{ fontSize: 18, fontWeight: 500, color: 'var(--ps-navy)', marginTop: 12 }}>Ready to synthesize</div>
          <div style={{ fontSize: 14.5, color: 'var(--fg-2)', marginTop: 8 }}>Generate the guide from your {reviewed.length} calls and comments.</div>
        </div>
      )}

      {guide && (
        <div style={{ marginTop: 28 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px', background: 'var(--ps-aqua-100)', color: 'var(--ps-aqua-700)', borderRadius: 10, fontSize: 13.5, marginBottom: 18 }}>
            <Icon name="sparkle" size={16} /> <span><b style={{ fontWeight: 600 }}>The judge is now calibrated from this guide.</b> Your next Calibrate round reflects it — watch the scoreboard agreement climb.</span>
          </div>
          {stale && (
            <div style={{ padding: '10px 16px', background: 'var(--ps-flag-soft)', color: 'var(--ps-flag-ink)', borderRadius: 10, fontSize: 13.5, marginBottom: 22, display: 'flex', alignItems: 'center', gap: 9 }}>
              <Icon name="refresh" size={15} /> Built from {guide.basedOn} reviews — you now have {reviewed.length}. Refresh to fold in the new ones.
            </div>
          )}

          {/* summary */}
          <div style={{ background: 'var(--ps-navy)', borderRadius: 18, padding: '28px 32px', marginBottom: 28, color: '#fff', position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, background: 'var(--wash-teal-frame)', opacity: .5, pointerEvents: 'none' }} />
            <div style={{ position: 'relative' }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ps-secondary-teal)', marginBottom: 12 }}>The taste, in a sentence</div>
              <div style={{ fontSize: 'clamp(19px,2.2vw,26px)', fontWeight: 500, lineHeight: 1.4, maxWidth: '46ch' }}>{guide.summary}</div>
            </div>
          </div>

          {/* do / don't */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 30 }} className="dd-grid">
            <RuleCol kind="do" items={guide.dos} />
            <RuleCol kind="dont" items={guide.donts} />
          </div>

          {/* looks like this / not this */}
          <Section title="Looks like this" sub="Your own keepers, highest brand-fit first.">
            <Gallery recs={liked.slice(0, 8)} tone="good" empty="No kept images yet." />
          </Section>
          <Section title="Not this" sub="The shots you passed on.">
            <Gallery recs={disliked.slice(0, 8)} tone="bad" empty="No rejected images yet." />
          </Section>

          {/* trends */}
          {guide.trends && guide.trends.length > 0 && (
            <Section title="Recurring trends" sub="Qualities that keep showing up in what you keep.">
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
                {guide.trends.map((t, i) => (
                  <div key={i} style={{ border: '1px solid var(--ps-line)', borderRadius: 12, padding: '14px 16px', background: 'var(--ps-white)', maxWidth: 280, boxShadow: 'var(--sh-1)' }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ps-primary-blue)', marginBottom: 5 }}>{t.tag}</div>
                    <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5 }}>{t.note}</div>
                  </div>
                ))}
              </div>
            </Section>
          )}

          {/* social-specific guidance */}
          {guide.social && (guide.social.note || (guide.social.rules && guide.social.rules.length > 0)) && (
            <Section title="Social & LinkedIn" sub="What your social-asset calls reveal — pairs with the Social playbook tab.">
              {guide.social.note && (
                <p style={{ fontSize: 15, color: 'var(--fg-1)', lineHeight: 1.6, margin: '0 0 14px', maxWidth: '64ch' }}>{guide.social.note}</p>
              )}
              {guide.social.rules && guide.social.rules.length > 0 && (
                <ul style={{ margin: 0, paddingLeft: 18, listStyle: 'none' }}>
                  {guide.social.rules.map((t, i) => (
                    <li key={i} style={{ fontSize: 14.5, lineHeight: 1.55, marginBottom: 11, color: 'var(--fg-1)', position: 'relative', paddingLeft: 4 }}>
                      <span style={{ position: 'absolute', left: -16, top: 7, width: 6, height: 6, borderRadius: 6, background: 'var(--ps-secondary-teal)' }} />{t}
                    </li>
                  ))}
                </ul>
              )}
            </Section>
          )}

          {/* channels */}
          {guide.channels && guide.channels.length > 0 && (
            <Section title="Where to use the keepers" sub="Auto-routing imagery into posts, newsletters and emails.">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(240px,1fr))', gap: 16 }}>
                {guide.channels.map((c, i) => (
                  <div key={i} style={{ border: '1px solid var(--ps-line)', borderRadius: 14, padding: '18px 20px', background: 'var(--ps-white)', boxShadow: 'var(--sh-1)' }}>
                    <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ps-navy)', marginBottom: 7 }}>{c.channel}</div>
                    <div style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.55, marginBottom: 11 }}>{c.guidance}</div>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, background: 'var(--ps-cloud-gray)', border: '1px solid var(--ps-line)', borderRadius: 6, padding: '3px 9px', color: 'var(--ps-dark-blue-700)' }}>{c.ratios}</span>
                  </div>
                ))}
              </div>
            </Section>
          )}

          {/* divergence / recalibration */}
          {guide.divergence && (
            <Section title="How your taste sharpens the brand guide" sub="Feed this back so the AI judge recalibrates to you.">
              <div style={{ background: 'var(--ps-cloud-gray)', border: '1px solid var(--ps-line)', borderLeft: '4px solid var(--ps-secondary-teal)', borderRadius: 12, padding: '18px 22px', fontSize: 15, lineHeight: 1.65, color: 'var(--fg-1)' }}>
                {guide.divergence}
              </div>
            </Section>
          )}

          <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 30 }}>
            Generated {new Date(guide.generatedAt).toLocaleString()} · from {guide.basedOn} reviewed images.
          </div>
        </div>
      )}
    </div>
  );
}

function Section({ title, sub, children }) {
  return (
    <section style={{ marginBottom: 34 }}>
      <h2 style={{ fontSize: 21, fontWeight: 500, margin: '0 0 4px', letterSpacing: '-.01em' }}>{title}</h2>
      {sub && <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 16px' }}>{sub}</p>}
      {children}
    </section>
  );
}

function RuleCol({ kind, items }) {
  const isDo = kind === 'do';
  return (
    <div className={isDo ? 'dd dd--do' : 'dd dd--dont'} style={{ borderRadius: 15, padding: '24px 26px', background: isDo ? '#EAF6F0' : '#FBEDEB' }}>
      <p style={{ fontWeight: 700, fontSize: 12, letterSpacing: '.12em', textTransform: 'uppercase', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: 8, color: isDo ? '#1F7A52' : 'var(--ps-flag-ink)' }}>
        <Icon name={isDo ? 'check' : 'x'} size={15} stroke={3} />{isDo ? 'Do' : "Don't"}
      </p>
      <ul style={{ margin: 0, paddingLeft: 18, listStyle: 'none' }}>
        {items.map((t, i) => (
          <li key={i} style={{ fontSize: 14.5, lineHeight: 1.55, marginBottom: 12, color: 'var(--fg-1)', position: 'relative', paddingLeft: 4 }}>
            <span style={{ position: 'absolute', left: -16, top: 7, width: 6, height: 6, borderRadius: 6, background: isDo ? 'var(--st-success)' : 'var(--ps-flag)' }} />{t}
          </li>
        ))}
      </ul>
    </div>
  );
}

function Gallery({ recs, tone, empty }) {
  if (!recs.length) return <p style={{ color: 'var(--fg-3)', fontSize: 14 }}>{empty}</p>;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(150px,1fr))', gap: 12 }}>
      {recs.map((r) => (
        <figure key={r.id} style={{ margin: 0, borderRadius: 12, overflow: 'hidden', position: 'relative',
          border: `2px solid ${tone === 'good' ? '#BFE6D4' : '#F0C9C3'}`, boxShadow: 'var(--sh-1)' }}>
          <img src={r.dataURL} alt={r.name} loading="lazy" decoding="async" style={{ width: '100%', aspectRatio: '4/3', objectFit: 'cover', display: 'block',
            filter: tone === 'bad' ? 'grayscale(.45) brightness(.92)' : 'none' }} />
          {r.user.comment && (
            <figcaption style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '16px 10px 8px',
              background: 'linear-gradient(to top, rgba(12,14,22,.86), transparent)', color: '#fff', fontSize: 11.5, lineHeight: 1.4 }}>
              “{r.user.comment.length > 60 ? r.user.comment.slice(0, 58) + '…' : r.user.comment}”
            </figcaption>
          )}
        </figure>
      ))}
    </div>
  );
}

window.StyleGuide = StyleGuide;
