// menove-patterns-airy2.jsx, Patterns, second density pass (P01-B).
// The principle hardens: one viz, one register, everything else is typography.
// Depends on menove-patterns.jsx + menove-patterns-airy.jsx + menove-final.jsx.

/* the report, a line of text, nothing more */
function PTBReportLine({ onOpen }) {
  return (
    <div onClick={onOpen} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '16px 26px 0', flex: 'none', cursor: onOpen ? 'pointer' : 'default' }}>
      <span style={{ fontSize: 12, fontWeight: 700, color: FB.aub }}>4 stones to your report</span>
      <span style={{ fontSize: 11, fontWeight: 600, color: FB.soft }}>· 26 set</span>
      <svg viewBox="0 0 24 24" fill="none" stroke={FB.aub} strokeWidth="2.2" style={{ width: 11, height: 11 }}><path d="M9 5l7 7-7 7" /></svg>
    </div>
  );
}

/* the culmination, her patterns, risen as a cairn. The page opens on it the way
   the home opens on the daily stone. Forming floats faint at the top; testing in
   iris; confirmed carries the base. The side labels are the filter. */
function PTBCairnMoment({ active, onSelect, compact, caption = true }) {
  const sc = compact ? .78 : 1;
  const shapes = [
    '50% 50% 50% 50% / 56% 56% 44% 44%',
    '54% 46% 52% 48% / 58% 56% 44% 42%',
    '62% 38% 50% 50% / 60% 68% 32% 40%',
    '58% 42% 56% 44% / 70% 66% 34% 30%',
  ];
  const bands = [
    { k: 'forming', n: 2, stones: [[42, 15], [56, 18]] },
    { k: 'testing', n: 2, stones: [[70, 21], [84, 24]] },
    { k: 'confirmed', n: 3, stones: [[98, 27], [114, 30], [130, 34]] },
  ];
  const stoneStyle = (k, [w, h], i) => {
    const base = { width: Math.round(w * sc), height: Math.round(h * sc), borderRadius: shapes[i % 4], transform: `rotate(${i % 2 ? -3 : 2.5}deg)`, position: 'relative', overflow: 'hidden' };
    if (k === 'forming') return { ...base, boxShadow: `inset 0 0 0 1.4px ${fbTint(FB.ink, .28)}` };
    return { ...base, background: k === 'testing' ? FB.iris : FB.aub };
  };
  const sheen = (k) => k === 'forming' ? null : (
    <span style={{ position: 'absolute', inset: 0, borderRadius: 'inherit', backgroundImage: `radial-gradient(115% 85% at 50% -20%, rgba(255,255,255,${k === 'testing' ? '.45' : '.26'}), transparent 54%), radial-gradient(130% 95% at 50% 125%, rgba(31,14,42,${k === 'testing' ? '.18' : '.38'}), transparent 58%)` }}></span>
  );
  let si = 0;
  const bandOpacity = (k) => active ? (active === k ? 1 : .5) : 1;
  return (
    <div style={{ padding: compact ? '16px 26px 0' : '26px 26px 0', flex: 'none' }}>
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: Math.round(5 * sc), paddingRight: 96 }}>
          {bands.map((b) => (
            <div key={b.k} onClick={onSelect ? () => onSelect(b.k) : undefined} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: Math.round(5 * sc), cursor: onSelect ? 'pointer' : 'default', opacity: bandOpacity(b.k), transition: 'opacity .4s ease' }}>
              {b.stones.map((s, j) => <span key={j} style={stoneStyle(b.k, s, si++)}>{sheen(b.k)}</span>)}
            </div>
          ))}
        </div>
        {/* the lifecycle, labeled where it lives, these are the filter */}
        <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: '8px 0 10px' }}>
          {bands.map((b) => (
            <div key={b.k} onClick={onSelect ? () => onSelect(b.k) : undefined} style={{ textAlign: 'left', cursor: onSelect ? 'pointer' : 'default', opacity: active && active !== b.k ? .55 : 1, transition: 'opacity .4s ease' }}>
              <div style={{
                fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', fontWeight: 700, whiteSpace: 'nowrap',
                color: active === b.k ? FB.ink : (onSelect ? FB.ink : FB.soft), opacity: active === b.k ? 1 : .85,
                borderBottom: active === b.k ? `2px solid ${FB.aub}` : '2px solid transparent', paddingBottom: 3, display: 'inline-flex', alignItems: 'center', gap: 5,
              }}>{b.k} · {b.n}{onSelect && active !== b.k ? <svg viewBox="0 0 24 24" fill="none" stroke={FB.soft} strokeWidth="2.4" style={{ width: 9, height: 9 }}><path d="M9 5l7 7-7 7" /></svg> : null}</div>
            </div>
          ))}
        </div>
      </div>
      {caption ? (
        <div style={{ fontFamily: FB.display, fontSize: 17, lineHeight: 1.45, color: FB.ink, textAlign: 'center', marginTop: 18, textWrap: 'balance' }}>
          Seven patterns, risen from twenty-six days.
        </div>
      ) : null}
    </div>
  );
}

/* the surfaced count, every pattern is a stone; the groups are the filter */
function PTBSurfaced({ active = 'confirmed' }) {
  const groups = [
    { k: 'confirmed', n: 3 },
    { k: 'testing', n: 2 },
    { k: 'forming', n: 2 },
  ];
  const stone = (k, i) => {
    const w = 15 + (i * 5) % 7, h = 10 + (i * 3) % 4;
    const base = { width: w, height: h, flex: 'none', borderRadius: TK_SHAPES[i % 4], transform: `rotate(${i % 2 ? -7 : 6}deg)` };
    if (k === 'confirmed') return { ...base, background: FB.aub };
    if (k === 'testing') return { ...base, background: fbTint(FB.iris, .85) };
    return { ...base, background: 'transparent', boxShadow: `inset 0 0 0 1.4px ${fbTint(FB.ink, .32)}` };
  };
  return (
    <div style={{ padding: '0 26px', marginBottom: 22 }}>
      <div style={{ fontFamily: FB.display, fontSize: 15.5, lineHeight: 1.5, color: FB.ink }}>Seven patterns have surfaced from your 26 days.</div>
      <div style={{ display: 'flex', gap: 28, marginTop: 14 }}>
        {groups.map((g) => (
          <div key={g.k} style={{ display: 'flex', flexDirection: 'column', gap: 8, opacity: g.k === active ? 1 : .45 }}>
            <div style={{ display: 'flex', gap: 5, alignItems: 'flex-end', height: 14 }}>
              {Array.from({ length: g.n }).map((_, i) => <span key={i} style={stone(g.k, i + (g.k === 'testing' ? 1 : g.k === 'forming' ? 3 : 0))}></span>)}
            </div>
            <span style={{
              fontSize: 11, fontWeight: 700, textTransform: 'capitalize', whiteSpace: 'nowrap',
              color: g.k === active ? FB.ink : FB.soft,
              borderBottom: g.k === active ? `2px solid ${FB.aub}` : '2px solid transparent', paddingBottom: 4, alignSelf: 'flex-start',
            }}>{g.k} · {g.n}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* the lifecycle, words, not pills; the active one underlined in aubergine */
function PTBFilter({ active = 'confirmed' }) {
  const counts = { confirmed: 3, testing: 2, forming: 2 };
  return (
    <div style={{ display: 'flex', gap: 22, padding: '0 26px', marginBottom: 18 }}>
      {['confirmed', 'testing', 'forming'].map((s) => (
        <span key={s} style={{
          fontSize: 12, fontWeight: 700, textTransform: 'capitalize', whiteSpace: 'nowrap',
          color: s === active ? FB.ink : FB.soft,
          borderBottom: s === active ? `2px solid ${FB.aub}` : '2px solid transparent', paddingBottom: 5,
        }}>{s} · {counts[s]}</span>
      ))}
    </div>
  );
}

/* secondary patterns, pure type; the evidence is already bold in the claim */
function PTBRow({ claim }) {
  return (
    <div style={{ padding: '17px 0', borderTop: `1px solid ${FB.line}`, display: 'flex', alignItems: 'center', gap: 14 }}>
      <div style={{ flex: 1, fontSize: 13.5, lineHeight: 1.6, color: FB.ink, textWrap: 'pretty' }}>{claim}</div>
      <svg viewBox="0 0 24 24" fill="none" stroke={FB.soft} strokeWidth="2" style={{ width: 13, height: 13, flex: 'none' }}><path d="M9 5l7 7-7 7" /></svg>
    </div>
  );
}

/* trying, a row, with the only other viz on the page (the 10-day strip) */
function PTBTryRow() {
  return (
    <div style={{ padding: '15px 0 0' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10 }}>
        <span style={{ fontSize: 13.5, fontWeight: 600, color: FB.ink }}>Magnesium, after dinner</span>
        <span style={{ fontSize: 11, fontWeight: 700, color: FB.soft, whiteSpace: 'nowrap' }}>Day 6 of 10</span>
      </div>
      <div style={{ fontSize: 12.5, lineHeight: 1.6, color: FB.body, marginTop: 4 }}>Testing against your 3am waking, your days will tell us.</div>
      <div style={{ marginTop: 10 }}><PTRow hits={[0, 1, 3, 4, 5]} n={10} /></div>
    </div>
  );
}

function PTBVerdictLine() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 17, paddingTop: 15, borderTop: `1px solid ${FB.line}` }}>
      <span style={{ flex: 1, fontSize: 12.5, lineHeight: 1.55, color: FB.body }}>New verdict, <b style={{ color: FB.ink }}>less fog reported on 3 of 4</b> walking test days.</span>
      <svg viewBox="0 0 24 24" fill="none" stroke={FB.soft} strokeWidth="2" style={{ width: 12, height: 12, flex: 'none' }}><path d="M9 5l7 7-7 7" /></svg>
    </div>
  );
}

/* ---------- the primary page, the culmination, plus the two living shelves ---------- */
function PatternsHomeFinal({ label = 'P01 · Patterns, home', onOpen, onReport }) {
  return (
    <PTFrame label={label}>
      <PTBReportLine onOpen={onReport} />
      <PTBCairnMoment onSelect={onOpen} />
      <div style={{ paddingTop: 8 }}>
        <PTAQuestion />
      </div>
      <div style={{ paddingTop: 36 }}>
        <div style={{ padding: '0 26px' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
            <FBEyebrow color={FB.soft}>What you're trying</FBEyebrow>
            <span style={{ fontSize: 11.5, fontWeight: 700, color: FB.plum, whiteSpace: 'nowrap' }}>Verdicts</span>
          </div>
          <PTBTryRow />
          <PTBVerdictLine />
        </div>
      </div>
      <div style={{ paddingTop: 32 }}>
        <div style={{ padding: '0 26px' }}>
          <FBEyebrow color={FB.soft}>What Mona is watching</FBEyebrow>
          <PTAWatchLine body={<span>Wine evenings and night sweats: <b style={{ color: FB.ink }}>4 paired days</b> so far. About 6 more make it speak.</span>} />
          <PTAWatchLine body={<span>Breakfast timing and your morning energy, blocked for now.</span>} unlock="2 minutes with Mona" />
        </div>
      </div>
      <div style={{ height: 8 }}></div>
    </PTFrame>
  );
}

/* ---------- the lifecycle pages, where the details live now ---------- */
function PatternsList({ filter = 'confirmed', label, onBack, onSelect, onChallenge }) {
  const cards = PT_PATTERNS[filter];
  const subs = {
    confirmed: 'Standing evidence, in your reported days.',
    testing: 'Holding their shape, so far.',
    forming: 'Early threads, a few more days make them speak.',
  };
  return (
    <div data-screen-label={label || `Patterns · ${filter}`} style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden', background: FB.paper, color: FB.ink, fontFamily: FB.sans, position: 'relative' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '16px 26px 0', fontSize: 12.5, fontWeight: 600, flex: 'none' }}>
        <span>9:41</span><span>5G · 76</span>
      </div>
      <div style={{ padding: '14px 26px 0', flex: 'none' }}>
        <div onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 700, color: FB.plum, cursor: 'pointer' }}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" style={{ width: 11, height: 11 }}><path d="M15 5l-7 7 7 7" /></svg>
          Patterns
        </div>
        <div style={{ fontFamily: FB.display, fontSize: 23, marginTop: 12, textTransform: 'capitalize' }}>{filter} · {cards.length}</div>
        <div style={{ fontSize: 12, fontWeight: 500, marginTop: 3, color: FB.soft }}>{subs[filter]}</div>
      </div>
      <PTBCairnMoment active={filter} onSelect={onSelect} compact caption={false} />
      <div style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
        <div style={{ paddingTop: 22 }}>
          <PTAFeature claim={cards[0].claim} chip={cards[0].chip} hits={cards[0].hits} challenge={cards[0].challenge} onChallenge={cards[0].challenge ? onChallenge : undefined} />
          <div style={{ padding: '20px 26px 0' }}>
            {cards.slice(1).map((c, i) => <PTARow key={i} claim={c.claim} hits={c.hits} />)}
          </div>
        </div>
      </div>
      <PTNav />
    </div>
  );
}

/* the room, home ⇄ lifecycle pages ⇄ sheets, in place */
function PatternsRoom({ label = 'P01 · Patterns, home' }) {
  const [view, setView] = React.useState(null);
  if (view === 'report') return <div onClick={() => setView(null)} style={{ width: '100%', height: '100%', cursor: 'pointer' }}><PatternsReportSheet /></div>;
  if (view === 'challenge') return <div onClick={() => setView('confirmed')} style={{ width: '100%', height: '100%', cursor: 'pointer' }}><PatternsChallengeSheet /></div>;
  if (view) return <PatternsList filter={view} label={`Patterns · ${view}`} onBack={() => setView(null)} onSelect={setView} onChallenge={() => setView('challenge')} />;
  return <PatternsHomeFinal label={label} onOpen={setView} onReport={() => setView('report')} />;
}

/* ---------- P01-B ---------- */
function PatternsHomeAiry2({ filter = 'confirmed', label = 'P01-B · Patterns, second pass' }) {
  const cards = PT_PATTERNS[filter];
  return (
    <PTFrame label={label}>
      <PTBReportLine />
      <PTBCairnMoment active={filter} />
      <div style={{ paddingTop: 6 }}>
        <PTAQuestion />
      </div>
      <div style={{ paddingTop: 30 }}>
        <PTAFeature claim={cards[0].claim} chip={cards[0].chip} hits={cards[0].hits} challenge={cards[0].challenge} />
        <div style={{ padding: '20px 26px 0' }}>
          {cards.slice(1).map((c, i) => <PTBRow key={i} claim={c.claim} />)}
        </div>
      </div>
      <div style={{ paddingTop: 38 }}>
        <div style={{ padding: '0 26px' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
            <FBEyebrow color={FB.soft}>What you're trying</FBEyebrow>
            <span style={{ fontSize: 11.5, fontWeight: 700, color: FB.plum, whiteSpace: 'nowrap' }}>Verdicts</span>
          </div>
          <PTBTryRow />
          <PTBVerdictLine />
        </div>
      </div>
      <div style={{ paddingTop: 38 }}>
        <div style={{ padding: '0 26px' }}>
          <FBEyebrow color={FB.soft}>What Mona is watching</FBEyebrow>
          <div style={{ fontSize: 12.5, lineHeight: 1.65, color: FB.body, marginTop: 12 }}>
            Wine evenings and night sweats: <b style={{ color: FB.ink }}>4 paired days</b> so far. About 6 more make it speak.
          </div>
          <div style={{ fontSize: 12.5, lineHeight: 1.65, color: FB.body, marginTop: 12 }}>
            Breakfast timing and your morning energy, blocked for now. <span style={{ fontWeight: 700, color: FB.plum, whiteSpace: 'nowrap' }}>2 minutes with Mona</span>
          </div>
        </div>
      </div>
      <div style={{ height: 30 }}></div>
    </PTFrame>
  );
}

Object.assign(window, { PatternsHomeAiry2, PTBCairnMoment, PTBReportLine, PTBFilter, PTBSurfaced, PTBRow, PTBTryRow, PTBVerdictLine, PatternsHomeFinal, PatternsList, PatternsRoom });

/* promote: the room is now the canonical PatternsHome everywhere it's rendered */
window.PatternsHomeDense = window.PatternsHome;
window.PatternsHome = PatternsRoom;
