// components.jsx — shared UI primitives for focyl LP

const { useEffect, useRef, useState, useMemo } = React;

/* ─── Reveal on scroll ─── */
function Reveal({ children, delay = 0, as: Tag = 'div', className = '', style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setTimeout(() => el.classList.add('in'), delay);
          io.disconnect();
        }
      });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <Tag ref={ref} className={`reveal ${className}`} style={style}>{children}</Tag>;
}

/* ─── Moon phase glyph (8 phases) ─── */
function MoonGlyph({ size = 18, phase = 0, color = 'var(--ink)' }) {
  // phase 0..7 :: new, waxingCrescent, firstQuarter, waxingGibbous, full, waningGibbous, lastQuarter, waningCrescent
  const r = size / 2;
  // circle that sits over the moon to carve its shape
  // we use two stacked circles + a clipping rect
  const styles = {
    width: size, height: size, borderRadius: '50%', position: 'relative', overflow: 'hidden',
    background: color, display: 'inline-block', flex: '0 0 auto',
  };
  // draw illuminated portion via inner circle offset
  // we approximate by overlaying a background-colored circle of varying offset/size
  const map = [
    /* new       */ { bg: 'var(--bg)', off: 0,    sz: 1 },
    /* wax cres. */ { bg: 'var(--bg)', off: -0.4, sz: 0.95 },
    /* first qtr */ { bg: 'var(--bg)', off: -0.5, sz: 1 },
    /* wax gibb. */ { bg: 'var(--bg)', off: -0.75, sz: 0.7 },
    /* full      */ { bg: color, off: 0, sz: 0 },
    /* wan gibb. */ { bg: 'var(--bg)', off: 0.75, sz: 0.7 },
    /* last qtr  */ { bg: 'var(--bg)', off: 0.5,  sz: 1 },
    /* wan cres. */ { bg: 'var(--bg)', off: 0.4,  sz: 0.95 },
  ];
  const m = map[phase];
  const inner = {
    position: 'absolute',
    top: '50%', left: '50%',
    width: size * m.sz, height: size * m.sz,
    transform: `translate(calc(-50% + ${m.off * size}px), -50%)`,
    background: m.bg, borderRadius: '50%',
  };
  if (phase === 4) return <span style={{ ...styles, background: color }} />;
  return <span style={styles}><span style={inner} /></span>;
}

/* ─── Phase chip ─── */
function PhaseChip({ phase, label, active = false }) {
  const colors = {
    mens: 'var(--p-mens)', foll: 'var(--p-foll)', ovul: 'var(--p-ovul)',
    lut1: 'var(--p-lut1)', lut2: 'var(--p-lut2)',
  };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '6px 12px', borderRadius: 999,
      background: active ? colors[phase] : 'transparent',
      color: active ? '#fff' : 'var(--ink-soft)',
      border: `1px solid ${active ? 'transparent' : 'var(--rule)'}`,
      fontSize: 11, fontFamily: 'var(--mono)', letterSpacing: '0.06em',
    }}>
      <span className="dot" style={{ background: colors[phase], width: 7, height: 7 }} />
      {label}
    </span>
  );
}

/* ─── Phone shell ─── */
function Phone({ children, width = 280, height = 580, time = '9:41' }) {
  return (
    <div className="phone" style={{ width, height }}>
      <div className="phone-screen">
        <div className="phone-notch" />
        <div className="phone-statusbar">
          <span>{time}</span>
          <span className="right">
            <svg width="14" height="9" viewBox="0 0 14 9" fill="none"><rect x="0" y="3" width="2" height="6" rx="0.5" fill="currentColor"/><rect x="4" y="2" width="2" height="7" rx="0.5" fill="currentColor"/><rect x="8" y="1" width="2" height="8" rx="0.5" fill="currentColor"/><rect x="12" y="0" width="2" height="9" rx="0.5" fill="currentColor"/></svg>
            <svg width="14" height="9" viewBox="0 0 14 9" fill="none"><path d="M7 1.5C4.5 1.5 2.3 2.5 1 4l1 1c1.1-1.2 2.9-2 5-2s3.9.8 5 2l1-1C11.7 2.5 9.5 1.5 7 1.5zm0 3C5.5 4.5 4.2 5 3.3 5.9l1 1c.7-.6 1.6-1 2.7-1s2 .4 2.7 1l1-1C9.8 5 8.5 4.5 7 4.5zm0 3c-.6 0-1.1.2-1.5.5L7 9l1.5-1.5c-.4-.3-.9-.5-1.5-.5z" fill="currentColor"/></svg>
            <svg width="22" height="10" viewBox="0 0 22 10" fill="none">
              <rect x="0.5" y="0.5" width="18" height="9" rx="2" stroke="currentColor" fill="none" opacity="0.5"/>
              <rect x="2" y="2" width="13" height="6" rx="1" fill="currentColor"/>
              <rect x="19.5" y="3.5" width="1.5" height="3" rx="0.5" fill="currentColor" opacity="0.5"/>
            </svg>
          </span>
        </div>
        <div style={{ flex: 1, padding: '14px 18px 22px', overflow: 'hidden', position: 'relative' }}>
          {children}
        </div>
      </div>
    </div>
  );
}

/* ─── Phase ring ─── */
function PhaseRing({ size = 200, currentPhase = 'lut1', day = 22, totalDays = 28 }) {
  // 5 segments: mens 0-5, foll 6-13, ovul 14-15, lut1 16-21, lut2 22-27
  const segs = [
    { id: 'mens', start: 0, end: 5, color: 'var(--p-mens)' },
    { id: 'foll', start: 5, end: 13, color: 'var(--p-foll)' },
    { id: 'ovul', start: 13, end: 15, color: 'var(--p-ovul)' },
    { id: 'lut1', start: 15, end: 21, color: 'var(--p-lut1)' },
    { id: 'lut2', start: 21, end: 28, color: 'var(--p-lut2)' },
  ];
  const cx = size / 2, cy = size / 2, r = size / 2 - 14;
  const pol = (a) => [cx + r * Math.cos(a - Math.PI / 2), cy + r * Math.sin(a - Math.PI / 2)];
  const arc = (s, e, color, dim) => {
    const a1 = (s / totalDays) * Math.PI * 2;
    const a2 = (e / totalDays) * Math.PI * 2;
    const [x1, y1] = pol(a1);
    const [x2, y2] = pol(a2);
    const large = a2 - a1 > Math.PI ? 1 : 0;
    return (
      <path key={s + '-' + e}
        d={`M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}`}
        stroke={color} strokeWidth={10} fill="none" strokeLinecap="round"
        opacity={dim ? 0.32 : 1}
      />
    );
  };
  const dayAngle = (day / totalDays) * Math.PI * 2;
  const [dx, dy] = pol(dayAngle);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      {segs.map(s => arc(s.start, s.end, s.color, s.id !== currentPhase))}
      <circle cx={dx} cy={dy} r={7} fill="var(--bg-card)" stroke="var(--ink)" strokeWidth={1.5} />
      <text x={cx} y={cy - 4} textAnchor="middle" fontFamily="var(--serif)" fontSize={28} fill="var(--ink)" fontWeight={400}>Day</text>
      <text x={cx} y={cy + 26} textAnchor="middle" fontFamily="var(--serif)" fontSize={36} fill="var(--ink)" fontWeight={500}>{day}</text>
    </svg>
  );
}

/* ─── 5×5 Heatmap (phases × domains × 17 symptoms approximated as 5 cells per row) ─── */
function Heatmap() {
  const phases = [
    { id: 'mens', label: '月経', color: 'var(--p-mens)' },
    { id: 'foll', label: '卵胞', color: 'var(--p-foll)' },
    { id: 'ovul', label: '排卵', color: 'var(--p-ovul)' },
    { id: 'lut1', label: '黄体前', color: 'var(--p-lut1)' },
    { id: 'lut2', label: '黄体後', color: 'var(--p-lut2)' },
  ];
  const domains = ['実行機能', '注意', '感情', '感覚', '身体'];
  // intensity matrix [phase][domain] 0..4
  const m = [
    [3, 2, 3, 2, 3],   // mens
    [1, 1, 1, 1, 1],   // foll  (best)
    [1, 1, 2, 2, 2],   // ovul
    [2, 2, 3, 2, 2],   // lut1
    [4, 4, 4, 3, 3],   // lut2 (worst)
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '64px repeat(5, 1fr)', gap: 6, fontSize: 11 }}>
      <div></div>
      {domains.map(d => (
        <div key={d} style={{ textAlign: 'center', color: 'var(--ink-mute)', fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.04em' }}>{d}</div>
      ))}
      {phases.map((p, i) => (
        <React.Fragment key={p.id}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-soft)', fontSize: 11 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: p.color }} />
            {p.label}
          </div>
          {domains.map((d, j) => {
            const v = m[i][j];
            return (
              <div key={d} style={{
                aspectRatio: '1 / 1',
                borderRadius: 6,
                background: p.color,
                opacity: 0.18 + v * 0.18,
                border: '1px solid var(--rule)',
              }} />
            );
          })}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ─── LogoMark — focyl のシンボルマーク (月 + 波) ─── */
function LogoMark({ size = 22, color = 'currentColor', strokeWidth = 1.8 }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke={color}
      strokeWidth={strokeWidth}
      strokeLinecap="round"
      style={{ display: 'inline-block', verticalAlign: 'middle' }}
    >
      {/* 月の半弧 */}
      <path d="M 3 12 A 9 9 0 0 1 21 12" />
      {/* 2周期の波 */}
      <path d="M 3 12 C 4.5 14.6, 6 14.6, 7.5 12 C 9 9.4, 10.5 9.4, 12 12 C 13.5 14.6, 15 14.6, 16.5 12 C 18 9.4, 19.5 9.4, 21 12" />
    </svg>
  );
}

Object.assign(window, { Reveal, MoonGlyph, PhaseChip, Phone, PhaseRing, Heatmap, LogoMark });
