// While² — macOS variants with glyph-scramble navigation
// 1. Menu-bar popover (interactive)  2. Full terminal window (interactive)

const _MAC_INK = '#e8e6df';

// Reuse glyph-scramble hook from while2-scramble.jsx
// (Scram component is exposed there but we redefine a slim version to avoid load-order coupling.)
const _MAC_POOL = '!<>-_\\/[]{}—=+*^?#·░▒▓█'.split('');
function _useMacScramble(target, key, dur = 520) {
  const [out, setOut] = React.useState(target);
  React.useEffect(() => {
    if (typeof target !== 'string') { setOut(target); return; }
    const start = performance.now();
    const reveals = Array.from({ length: target.length }, (_, i) => {
      const wave = (i / Math.max(1, target.length)) * 0.55;
      const jitter = Math.random() * 0.45;
      return (wave + jitter) * dur;
    });
    let raf;
    const tick = () => {
      const t = performance.now() - start;
      let s = '';
      for (let i = 0; i < target.length; i++) {
        const ch = target[i];
        if (ch === ' ' || ch === '\n') { s += ch; continue; }
        s += t >= reveals[i] ? ch : _MAC_POOL[Math.floor(Math.random() * _MAC_POOL.length)];
      }
      setOut(s);
      if (t < dur) raf = requestAnimationFrame(tick);
      else setOut(target);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [key, target, dur]);
  return out;
}
const _S = ({ text, k, dur, style }) => {
  const out = _useMacScramble(text, k, dur);
  return <span style={style}>{out}</span>;
};

// Desktop wallpaper
function _Desktop({ children, w = 1280, h = 800 }) {
  return (
    <div style={{
      width: w, height: h, position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(165deg, #2a4a6e 0%, #142840 50%, #050d1a 100%)',
      borderRadius: 8,
      fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro", sans-serif',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 30% 20%, rgba(120,200,255,0.18) 0%, transparent 55%)',
      }} />
      {children}
    </div>
  );
}

function _MenuBar({ activeIcon = false }) {
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0, height: 28,
      background: 'rgba(20,30,45,0.55)',
      backdropFilter: 'blur(20px) saturate(160%)',
      WebkitBackdropFilter: 'blur(20px) saturate(160%)',
      borderBottom: '0.5px solid rgba(255,255,255,0.08)',
      display: 'flex', alignItems: 'center', padding: '0 8px',
      fontSize: 13, color: '#fff', letterSpacing: '0.01em', zIndex: 5,
    }}>
      <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
        <span style={{ fontSize: 14 }}></span>
        <span style={{ fontWeight: 600 }}>While²</span>
        <span style={{ opacity: 0.85 }}>File</span>
        <span style={{ opacity: 0.85 }}>Edit</span>
        <span style={{ opacity: 0.85 }}>View</span>
        <span style={{ opacity: 0.85 }}>Help</span>
      </div>
      <div style={{ flex: 1 }} />
      <div style={{ display: 'flex', gap: 14, alignItems: 'center', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace' }}>
        <span style={{ opacity: 0.7, fontSize: 11 }}>↑↓</span>
        <span style={{ opacity: 0.7, fontSize: 11 }}>◐</span>
        <span style={{ opacity: 0.7, fontSize: 11 }}>📶</span>
        <span style={{ opacity: 0.7, fontSize: 11 }}>🔋</span>
        <span style={{
          padding: '4px 8px', borderRadius: 4, marginLeft: 4,
          background: activeIcon ? 'rgba(74,222,222,0.25)' : 'transparent',
          color: activeIcon ? '#7ce8e8' : '#fff',
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
          fontSize: 11, letterSpacing: '0.04em',
        }}>w²</span>
        <span style={{ opacity: 0.85, fontSize: 12 }}>Mon 10:24</span>
      </div>
    </div>
  );
}

function _PopoverArrow({ left }) {
  return (
    <div style={{ position: 'absolute', top: -6, left, width: 12, height: 6, overflow: 'hidden' }}>
      <div style={{
        width: 12, height: 12, background: '#000',
        transform: 'rotate(45deg) translateY(50%)',
        border: '0.5px solid rgba(255,255,255,0.08)',
      }} />
    </div>
  );
}

// ── Popover bodies (compact, scramble-aware) ──
function _PopToday({ k }) {
  const today = [
    { name: 'burnable trash', rule: 'weekly · tue' },
    { name: 'stretch',        rule: 'daily' },
    { name: 'haircut',        rule: 'every 4w · overdue', warn: true },
  ];
  const upcoming = [
    { t: '04/30', name: 'non-burnable trash', rule: 'biweekly' },
    { t: '05/03', name: 'pay rent',           rule: 'monthly · 3' },
    { t: '05/05', name: 'restock shampoo',    rule: 'every 6w' },
  ];
  return (
    <div>
      <div style={{ padding: '14px 16px 4px' }}>
        <div style={{ fontSize: 9, color: 'rgba(232,230,223,0.45)', letterSpacing: '0.16em', marginBottom: 4 }}>
          <_S text="// today" k={k} />
        </div>
        {today.map((t, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '1fr auto', gap: 8,
            padding: '6px 0', fontSize: 11, lineHeight: 1.4,
            color: t.warn ? W2.cyan : _MAC_INK,
          }}>
            <_S text={t.name} k={k} dur={520 + i * 60} />
            <_S text={t.rule} k={k} dur={520 + i * 60}
              style={{ fontSize: 9.5, color: t.warn ? W2.cyan : 'rgba(232,230,223,0.45)' }} />
          </div>
        ))}
      </div>
      <div style={{ padding: '12px 16px 6px' }}>
        <div style={{ fontSize: 9, color: 'rgba(232,230,223,0.45)', letterSpacing: '0.16em', marginBottom: 4 }}>
          <_S text="// upcoming" k={k} />
        </div>
        {upcoming.map((t, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '46px 1fr auto', gap: 8,
            padding: '5px 0', fontSize: 11, lineHeight: 1.4,
          }}>
            <_S text={t.t} k={k} dur={580 + i * 60} style={{ color: 'rgba(232,230,223,0.55)' }} />
            <_S text={t.name} k={k} dur={580 + i * 60} />
            <_S text={t.rule} k={k} dur={580 + i * 60}
              style={{ fontSize: 9.5, color: 'rgba(232,230,223,0.45)' }} />
          </div>
        ))}
      </div>
    </div>
  );
}

function _PopNew({ k }) {
  const Field = ({ kk, v, hint }) => (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
        <span style={{ width: 64, fontSize: 11, color: 'rgba(232,230,223,0.55)' }}>
          <_S text={kk} k={k} />
        </span>
        <span style={{ flex: 1, fontSize: 11, color: _MAC_INK,
          borderBottom: '1px dotted rgba(232,230,223,0.25)', paddingBottom: 3 }}>
          <_S text={v} k={k} dur={620} />
        </span>
      </div>
      {hint && (
        <div style={{ marginTop: 3, marginLeft: 76, fontSize: 9, color: 'rgba(232,230,223,0.4)' }}>
          <_S text={hint} k={k} />
        </div>
      )}
    </div>
  );
  return (
    <div style={{ padding: '20px 16px 8px' }}>
      <Field kk="name"  v="haircut" />
      <Field kk="every" v="4 weeks"    hint="days · weeks · months" />
      <Field kk="from"  v="completion" hint="completion · fixed date" />
      <div style={{ marginTop: 10, fontSize: 10, color: 'rgba(232,230,223,0.5)', lineHeight: 1.6 }}>
        <span style={{ color: W2.cyan }}>?</span>{' '}
        <_S text="done 04/28 → next 05/26 → 06/23 …" k={k} dur={680} />
      </div>
    </div>
  );
}

function _PopConfig({ k }) {
  const rows = [
    ['operator',    'user.local'],
    ['timezone',    'asia/tokyo'],
    ['notify_at',   '09:00'],
    ['theme',       'dark.cyan'],
    ['icloud',      'on'],
    ['last_synced', '2 min ago'],
  ];
  return (
    <div style={{ padding: '16px 16px 8px' }}>
      {rows.map(([kk, v], i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '100px auto 1fr',
          fontSize: 11, lineHeight: 1.85,
        }}>
          <span style={{ color: 'rgba(232,230,223,0.55)' }}>
            <_S text={kk} k={k} dur={500 + i * 30} />
          </span>
          <span style={{ color: 'rgba(232,230,223,0.3)', padding: '0 8px' }}>=</span>
          <span style={{ color: _MAC_INK }}>
            <_S text={v} k={k} dur={520 + i * 30} />
          </span>
        </div>
      ))}
    </div>
  );
}

function _PopoverInteractive() {
  const [screen, setScreen] = React.useState('today');
  const [tick, setTick] = React.useState(0);
  const goto = (next) => {
    if (next === screen) return;
    setScreen(next);
    setTick(t => t + 1);
  };
  const k = `${screen}-${tick}`;
  const promptText = screen === 'today' ? 'today' : screen === 'new' ? 'new_' : 'config';

  return (
    <div style={{
      width: 360, background: '#000', color: _MAC_INK,
      fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
      borderRadius: 12, overflow: 'hidden',
      boxShadow: '0 18px 60px rgba(0,0,0,0.55), 0 0 0 0.5px rgba(255,255,255,0.08)',
      border: '0.5px solid rgba(255,255,255,0.08)',
      position: 'relative',
    }}>
      <div className="w2-scan" />
      <div style={{ padding: '14px 16px 0', fontSize: 11, lineHeight: 1.6 }}>
        <span style={{ color: W2.cyan }}>&gt;</span> while²{' '}
        <_S text={promptText} k={k} dur={420} />
        <span className="w2-blink" style={{ marginLeft: 2 }}>_</span>
      </div>

      {screen === 'today'  && <_PopToday  k={k} />}
      {screen === 'new'    && <_PopNew    k={k} />}
      {screen === 'config' && <_PopConfig k={k} />}

      <div style={{
        padding: '10px 16px', borderTop: '1px solid rgba(232,230,223,0.08)',
        fontSize: 10, display: 'flex', justifyContent: 'space-between',
        color: 'rgba(232,230,223,0.55)',
      }}>
        {[
          ['today',  'today'],
          ['new',    '+ new_'],
          ['config', 'config'],
        ].map(([id, label]) => (
          <span key={id} onClick={() => goto(id)} style={{
            cursor: 'pointer', userSelect: 'none',
            color: screen === id ? W2.cyan : 'rgba(232,230,223,0.55)',
          }}>
            {screen === id ? <span style={{ color: W2.cyan }}>&gt; </span> : '  '}
            {label}
          </span>
        ))}
      </div>
    </div>
  );
}

// ── Variant 1 — Menu bar popover ──
function MacMenuBar() {
  return (
    <_Desktop w={1280} h={800}>
      <_MenuBar activeIcon />
      <div style={{ position: 'absolute', top: 36, right: 92, zIndex: 6 }}>
        <_PopoverArrow left={300} />
        <_PopoverInteractive />
      </div>
      <div style={{
        position: 'absolute', bottom: 12, left: '50%', transform: 'translateX(-50%)',
        height: 56, width: 320, borderRadius: 16,
        background: 'rgba(255,255,255,0.08)',
        backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
        border: '0.5px solid rgba(255,255,255,0.12)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      }}>
        {[1,2,3,4,5,6,7].map(i => (
          <div key={i} style={{
            width: 36, height: 36, borderRadius: 8,
            background: 'rgba(255,255,255,0.18)',
          }} />
        ))}
      </div>
    </_Desktop>
  );
}

// ── Terminal window bodies (scramble-aware) ──
function _TermToday({ k }) {
  const today = [
    { name: 'burnable trash',  rule: 'weekly · tue' },
    { name: 'stretch',         rule: 'daily' },
    { name: 'haircut',         rule: 'every 4w · overdue', warn: true },
  ];
  const upcoming = [
    { t: '04/30', name: 'non-burnable trash', rule: 'biweekly' },
    { t: '05/03', name: 'pay rent',           rule: 'monthly · 3' },
    { t: '05/05', name: 'restock shampoo',    rule: 'every 6w' },
    { t: '05/06', name: 'book checkup',       rule: 'every 12m' },
  ];
  return (
    <>
      <div style={{ marginBottom: 4, fontSize: 10, color: 'rgba(232,230,223,0.45)', letterSpacing: '0.16em' }}>
        <_S text="// today" k={k} />
      </div>
      {today.map((t, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 10,
          fontSize: 12, padding: '3px 0',
          color: t.warn ? W2.cyan : _MAC_INK,
        }}>
          <span style={{ color: t.warn ? W2.cyan : 'rgba(232,230,223,0.4)' }}>[{i + 1}]</span>
          <_S text={t.name} k={k} dur={520 + i * 60} />
          <_S text={t.rule} k={k} dur={520 + i * 60}
            style={{ fontSize: 10, color: t.warn ? W2.cyan : 'rgba(232,230,223,0.45)' }} />
        </div>
      ))}
      <div style={{ margin: '14px 0 4px', fontSize: 10, color: 'rgba(232,230,223,0.45)', letterSpacing: '0.16em' }}>
        <_S text="// upcoming" k={k} />
      </div>
      {upcoming.map((t, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '52px 1fr auto', gap: 10,
          fontSize: 12, padding: '3px 0',
        }}>
          <_S text={t.t} k={k} dur={580 + i * 50} style={{ color: 'rgba(232,230,223,0.55)' }} />
          <_S text={t.name} k={k} dur={580 + i * 50} />
          <_S text={t.rule} k={k} dur={580 + i * 50}
            style={{ fontSize: 10, color: 'rgba(232,230,223,0.45)' }} />
        </div>
      ))}
    </>
  );
}

function _TermNew({ k }) {
  const Field = ({ kk, v, hint }) => (
    <div style={{ marginBottom: 16 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
        <span style={{ width: 80, fontSize: 12, color: 'rgba(232,230,223,0.55)' }}>
          <_S text={kk} k={k} />
        </span>
        <span style={{ flex: 1, fontSize: 13, color: _MAC_INK,
          borderBottom: '1px dotted rgba(232,230,223,0.25)', paddingBottom: 4 }}>
          <_S text={v} k={k} dur={620} />
        </span>
      </div>
      {hint && (
        <div style={{ marginTop: 4, marginLeft: 94, fontSize: 10, color: 'rgba(232,230,223,0.4)' }}>
          <_S text={hint} k={k} />
        </div>
      )}
    </div>
  );
  return (
    <div style={{ paddingTop: 6 }}>
      <Field kk="name"  v="haircut" />
      <Field kk="every" v="4 weeks"    hint="days · weeks · months" />
      <Field kk="from"  v="completion" hint="completion · fixed date" />
      <div style={{ marginTop: 12, fontSize: 11, color: 'rgba(232,230,223,0.5)', lineHeight: 1.7 }}>
        <span style={{ color: W2.cyan }}>?</span>{' '}
        <_S text="done 04/28 → next 05/26 → 06/23 …" k={k} dur={680} />
      </div>
    </div>
  );
}

function _TermConfig({ k }) {
  const rows = [
    ['operator',      'user.local'],
    ['timezone',      'asia/tokyo'],
    ['week_starts',   'mon'],
    [null, null],
    ['notify_at',     '09:00'],
    ['recap_at',      '21:00'],
    ['overdue_ping',  'on'],
    [null, null],
    ['theme',         'dark.cyan'],
    ['reduce_motion', 'off'],
    [null, null],
    ['icloud',        'on'],
    ['last_synced',   '2 min ago'],
  ];
  return (
    <div style={{ paddingTop: 4 }}>
      {rows.map(([kk, v], i) => kk === null ? (
        <div key={i} style={{ height: 8 }} />
      ) : (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '140px auto 1fr',
          fontSize: 12, lineHeight: 1.8,
        }}>
          <span style={{ color: 'rgba(232,230,223,0.55)' }}>
            <_S text={kk} k={k} dur={500 + i * 25} />
          </span>
          <span style={{ color: 'rgba(232,230,223,0.3)', padding: '0 8px' }}>=</span>
          <span style={{ color: _MAC_INK }}>
            <_S text={v} k={k} dur={520 + i * 25} />
          </span>
        </div>
      ))}
    </div>
  );
}

// ── Variant 2 — Full terminal window (interactive) ──
function MacTerminal() {
  const [screen, setScreen] = React.useState('today');
  const [tick, setTick] = React.useState(0);
  const goto = (next) => {
    if (next === screen) return;
    setScreen(next);
    setTick(t => t + 1);
  };
  const k = `${screen}-${tick}`;
  const cmd = screen === 'today' ? 'ls today' : screen === 'new' ? 'new --interactive' : 'config';

  return (
    <_Desktop w={1280} h={800}>
      <_MenuBar />
      <div style={{ position: 'absolute', top: 80, left: '50%', transform: 'translateX(-50%)' }}>
        <div style={{
          width: 760, height: 480, borderRadius: 12, overflow: 'hidden',
          background: '#000', color: _MAC_INK,
          boxShadow: '0 24px 80px rgba(0,0,0,0.5), 0 0 0 0.5px rgba(255,255,255,0.08)',
          border: '0.5px solid rgba(255,255,255,0.08)',
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
          display: 'flex', flexDirection: 'column', position: 'relative',
        }}>
          <div className="w2-scan" />
          {/* title bar */}
          <div style={{
            height: 32, display: 'flex', alignItems: 'center',
            padding: '0 12px', gap: 8,
            borderBottom: '0.5px solid rgba(255,255,255,0.06)',
            background: 'rgba(255,255,255,0.02)',
          }}>
            <div style={{ display: 'flex', gap: 6 }}>
              <span style={{ width: 12, height: 12, borderRadius: '50%', background: '#ff5f57' }} />
              <span style={{ width: 12, height: 12, borderRadius: '50%', background: '#febc2e' }} />
              <span style={{ width: 12, height: 12, borderRadius: '50%', background: '#28c940' }} />
            </div>
            <div style={{ flex: 1, textAlign: 'center', fontSize: 11, color: 'rgba(232,230,223,0.5)' }}>
              while²@local — {screen} — 80×24
            </div>
          </div>

          {/* body */}
          <div style={{ flex: 1, padding: '20px 24px', fontSize: 12, lineHeight: 1.55, overflow: 'hidden' }}>
            <div style={{ marginBottom: 12 }}>
              <span style={{ color: W2.cyan }}>while²@local</span>
              <span style={{ color: 'rgba(232,230,223,0.4)' }}> ~ </span>
              <span>$ </span>
              <_S text={cmd} k={k} dur={420} />
            </div>

            {screen === 'today'  && <_TermToday  k={k} />}
            {screen === 'new'    && <_TermNew    k={k} />}
            {screen === 'config' && <_TermConfig k={k} />}

            <div style={{ marginTop: 18 }}>
              <span style={{ color: W2.cyan }}>while²@local</span>
              <span style={{ color: 'rgba(232,230,223,0.4)' }}> ~ </span>
              <span>$ </span>
              <span className="w2-blink" style={{ background: _MAC_INK, color: '#000', padding: '0 4px' }}>_</span>
            </div>
          </div>

          {/* footer nav */}
          <div style={{
            padding: '8px 16px', fontSize: 11,
            borderTop: '0.5px solid rgba(255,255,255,0.06)',
            color: 'rgba(232,230,223,0.5)',
            display: 'flex', justifyContent: 'space-between',
          }}>
            <div style={{ display: 'flex', gap: 18 }}>
              {[
                ['today',  'today'],
                ['new',    'new_'],
                ['config', 'config'],
              ].map(([id, label]) => (
                <span key={id} onClick={() => goto(id)} style={{
                  cursor: 'pointer', userSelect: 'none',
                  color: screen === id ? W2.cyan : 'rgba(232,230,223,0.55)',
                }}>
                  {screen === id ? <span style={{ color: W2.cyan }}>&gt; </span> : '  '}
                  {label}
                </span>
              ))}
            </div>
            <span>iCloud · synced 2m ago</span>
          </div>
        </div>
      </div>
    </_Desktop>
  );
}

window.MacMenuBar = MacMenuBar;
window.MacTerminal = MacTerminal;
window._PopToday = _PopToday;
window._PopNew = _PopNew;
window._PopConfig = _PopConfig;
