// ripen_remix.jsx — ランダム掛け合わせ
// 過去メモから2-3件ランダムに拾って並べ、「この2つ、つなげてみたら？」という刺激を出す。
// 1日1回シード固定（= 同じ日なら同じ組み合わせ）、手動シャッフル可能。
// AI は使わない（コスト・レイテンシ回避）。純ランダム + シード固定。

// 日付 + シャッフル回数でシードを作る。同じ日・同じ回数なら同じ組み合わせ。
function dailySeed(shuffleCount = 0) {
  const d = new Date();
  const key = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
  let h = shuffleCount * 2654435761;
  for (let i = 0; i < key.length; i++) {
    h = Math.imul(h ^ key.charCodeAt(i), 2654435761);
  }
  return (h >>> 0);
}

// Mulberry32 — 小さな決定的 PRNG
function mulberry32(seed) {
  return function () {
    let t = (seed += 0x6D2B79F5);
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// 配列からランダムにn個ピック（seedベース）
function seededPick(arr, n, rng) {
  const pool = arr.slice();
  const picked = [];
  for (let i = 0; i < n && pool.length > 0; i++) {
    const idx = Math.floor(rng() * pool.length);
    picked.push(pool.splice(idx, 1)[0]);
  }
  return picked;
}

// Ripen のトップに置く「再会 Digest」セクションを大きく目立たせるラッパ
function DigestHero({ notes, onUpdate, onDelete }) {
  const t = useT();
  const [digest, setDigest] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [openTheme, setOpenTheme] = React.useState(null);

  React.useEffect(() => {
    (async () => {
      setLoading(true);
      try {
        const d = await getDigest(notes);
        setDigest(d);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const refresh = async () => {
    setLoading(true);
    try {
      const d = await getDigest(notes, { forceRefresh: true });
      setDigest(d);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <section style={{
        background: t.bgCard, border: `1px dashed ${t.line}`,
        borderRadius: 18, padding: '28px 24px',
        fontFamily: APP_FONT,
      }}>
        <div style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '0.14em',
          color: t.ink4, marginBottom: 6,
        }}>ECHO · 今週の再会</div>
        <div style={{ fontSize: 13, color: t.ink4 }}>生成中…</div>
      </section>
    );
  }

  const hasThemes = digest && digest.themes && digest.themes.length > 0;
  const notesById = {};
  notes.forEach(n => { notesById[n.id] = n; });

  return (
    <section style={{
      background: `linear-gradient(180deg, ${t.primarySoft} 0%, ${t.bgCard} 100%)`,
      border: `1px solid ${t.primary}33`,
      borderRadius: 18, padding: '28px 24px',
      fontFamily: APP_FONT,
      boxShadow: t.shadow,
    }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        gap: 12, marginBottom: 16,
      }}>
        <div>
          <div style={{
            fontSize: 11, fontWeight: 800, letterSpacing: '0.18em',
            color: t.primary, marginBottom: 6,
          }}>ECHO · 今週の再会</div>
          <div style={{
            fontSize: 22, fontWeight: 800, letterSpacing: '-0.04em',
            color: t.ink, lineHeight: 1.25, textWrap: 'balance',
          }}>
            この1週間、繰り返し書いていたこと
          </div>
        </div>
        <button
          onClick={refresh}
          style={{
            background: 'transparent', border: 'none', color: t.ink4,
            fontSize: 11, cursor: 'pointer', fontFamily: APP_FONT,
            padding: 4, flexShrink: 0,
          }}>
          更新
        </button>
      </div>

      {!hasThemes && (
        <div style={{
          fontSize: 13, color: t.ink3, lineHeight: 1.6,
          padding: '8px 0',
        }}>
          まだ繰り返しのテーマが見つからない。<br/>
          投下を続けると、ここに静かに戻ってくる。
        </div>
      )}

      {hasThemes && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {digest.themes.map((th, i) => {
            const isOpen = openTheme === i;
            const members = th.ids.map(id => notesById[id]).filter(Boolean);
            return (
              <div key={i} style={{
                background: t.bgCard,
                border: `1px solid ${t.line}`,
                borderRadius: 12,
                padding: '14px 16px',
              }}>
                <button
                  onClick={() => setOpenTheme(isOpen ? null : i)}
                  style={{
                    background: 'transparent', border: 'none',
                    width: '100%', textAlign: 'left', padding: 0,
                    cursor: 'pointer', fontFamily: APP_FONT,
                    WebkitTapHighlightColor: 'transparent',
                  }}>
                  <div style={{
                    display: 'flex', alignItems: 'baseline', gap: 10,
                    marginBottom: 4,
                  }}>
                    <div style={{
                      fontSize: 16, fontWeight: 800, color: t.ink,
                      letterSpacing: '-0.03em',
                    }}>{th.name}</div>
                    <div style={{
                      fontSize: 11, color: t.ink4,
                    }}>{members.length}件</div>
                  </div>
                  {th.insight && (
                    <div style={{
                      fontSize: 13, color: t.ink3,
                      lineHeight: 1.55, letterSpacing: '-0.01em',
                    }}>{th.insight}</div>
                  )}
                </button>
                {isOpen && (
                  <div style={{
                    display: 'flex', flexDirection: 'column', gap: 8,
                    marginTop: 12,
                    paddingTop: 12, borderTop: `1px solid ${t.line}`,
                  }}>
                    {members.sort((a, b) => b.ts - a.ts).map(n => (
                      <NoteCard key={n.id} note={n} onUpdate={onUpdate} onDelete={onDelete}/>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </section>
  );
}

// ランダム掛け合わせ: 過去メモから2-3件を偶然のペアで見せる
// 同じ日なら同じ組み合わせが出る（シード固定）。シャッフルボタンでカウンタ++してリロール。
function RandomRemix({ notes, onUpdate, onDelete }) {
  const t = useT();
  // resting のメモは除外。直近3日は除外（記憶が新しすぎて「再会感」が薄い）
  const NOW = Date.now();
  const MIN_AGE = 3 * 24 * 3600 * 1000;
  const pool = notes.filter(n => n.status !== 'resting' && (NOW - n.ts) > MIN_AGE);

  const [shuffleCount, setShuffleCount] = React.useState(0);

  const picks = React.useMemo(() => {
    if (pool.length < 2) return [];
    const rng = mulberry32(dailySeed(shuffleCount));
    // 2件 or 3件をランダムに（pool が少ないなら2件固定）
    const size = pool.length >= 6 ? (rng() > 0.5 ? 3 : 2) : 2;
    return seededPick(pool, size, rng);
  }, [pool.length, shuffleCount, notes.length]);

  if (pool.length < 2) return null;

  return (
    <section style={{
      background: t.bgCard, border: `1px solid ${t.line}`,
      borderRadius: 16, padding: '20px 22px',
      fontFamily: APP_FONT,
    }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        gap: 12, marginBottom: 4,
      }}>
        <div>
          <div style={{
            fontSize: 10, fontWeight: 800, letterSpacing: '0.16em',
            color: t.purple2, marginBottom: 4,
          }}>REMIX · 今日の掛け合わせ</div>
          <div style={{
            fontSize: 16, fontWeight: 800, letterSpacing: '-0.03em',
            color: t.ink, lineHeight: 1.3,
          }}>
            この{picks.length}つ、つなげてみたら？
          </div>
        </div>
        <button
          onClick={() => setShuffleCount(c => c + 1)}
          title="別の組み合わせを見る"
          style={{
            background: 'transparent',
            border: `1px solid ${t.line}`,
            color: t.ink3,
            fontSize: 11, fontWeight: 600, fontFamily: APP_FONT,
            cursor: 'pointer',
            padding: '6px 10px', borderRadius: 8,
            letterSpacing: '-0.01em',
            display: 'inline-flex', alignItems: 'center', gap: 4,
            flexShrink: 0,
            WebkitTapHighlightColor: 'transparent',
          }}>
          ⟳ 振り直し
        </button>
      </div>

      <div style={{
        fontSize: 11, color: t.ink4, marginBottom: 14,
      }}>偶然の並びから、思ってもみなかった線が引けるかもしれない。</div>

      <div style={{
        display: 'flex', flexDirection: 'column', gap: 10,
        position: 'relative',
      }}>
        {picks.map((n, i) => (
          <React.Fragment key={n.id}>
            <NoteCard note={n} onUpdate={onUpdate} onDelete={onDelete}/>
            {i < picks.length - 1 && (
              <div style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '2px 0',
              }}>
                <div style={{ height: 1, flex: 1, background: t.line }}/>
                <div style={{
                  fontSize: 16, color: t.purple2, fontWeight: 800,
                  letterSpacing: '0.1em',
                }}>×</div>
                <div style={{ height: 1, flex: 1, background: t.line }}/>
              </div>
            )}
          </React.Fragment>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { DigestHero, RandomRemix, dailySeed, mulberry32, seededPick });
