/* global React */
// Skyhearth mobile — shared primitives reused across all directions.
// Exposed on window for the per-direction screen files.

const SH_EL = {
  fire:      { name: 'Fire',      glyph: '△', color: '#b8632a', icon: 'assets/icons/fire.png' },
  water:     { name: 'Water',     glyph: '~', color: '#355e7d', icon: 'assets/icons/water.png' },
  earth:     { name: 'Earth',     glyph: '□', color: '#7a5230', icon: 'assets/icons/earth.png' },
  nature:    { name: 'Nature',    glyph: '✿', color: '#5d7a3f', icon: 'assets/icons/nature.png' },
  ice:       { name: 'Ice',       glyph: '◊', color: '#5a7d9a', icon: 'assets/icons/ice.png' },
  lightning: { name: 'Lightning', glyph: '╱', color: '#9a7d2a', icon: 'assets/icons/lightning.png' },
  wind:      { name: 'Wind',      glyph: '≋', color: '#2a6f8a', icon: 'assets/icons/wind.png' },
  holy:      { name: 'Holy',      glyph: '✦', color: '#8c7a3a', icon: 'assets/icons/holy.png' },
};
// ring order, clockwise from top
const SH_RING = ['fire', 'water', 'earth', 'nature', 'ice', 'lightning', 'wind', 'holy'];
const SH_UNLOCKED = { fire: true, water: true, earth: true, nature: true };

// ---------- Android status bar ----------
function AndroidStatus({ time = '9:41' }) {
  return (
    <div className="android-status">
      <span className="clock">{time}</span>
      <span className="sys">
        {/* signal */}
        <svg width="15" height="11" viewBox="0 0 15 11"><g fill="#1a2e4a">
          <rect x="0" y="8" width="2.4" height="3" rx="0.4"/><rect x="3.6" y="5.5" width="2.4" height="5.5" rx="0.4"/>
          <rect x="7.2" y="3" width="2.4" height="8" rx="0.4"/><rect x="10.8" y="0.5" width="2.4" height="10.5" rx="0.4"/>
        </g></svg>
        {/* wifi */}
        <svg width="14" height="11" viewBox="0 0 14 11"><g fill="none" stroke="#1a2e4a" strokeWidth="1.3">
          <path d="M1 3.4a9 9 0 0112 0"/><path d="M3.2 5.8a5.6 5.6 0 017.6 0"/></g>
          <circle cx="7" cy="9" r="1.1" fill="#1a2e4a"/>
        </svg>
        {/* battery */}
        <svg width="22" height="11" viewBox="0 0 22 11"><rect x="0.6" y="0.6" width="18" height="9.8" rx="2" fill="none" stroke="#1a2e4a" strokeWidth="1.1"/><rect x="2.2" y="2.2" width="13" height="6.6" rx="0.8" fill="#1a2e4a"/><rect x="19.4" y="3.4" width="1.8" height="4.2" rx="0.9" fill="#1a2e4a"/></svg>
      </span>
    </div>
  );
}

// ---------- mini day dial (the persistent diurnal clock) ----------
function MiniDayDial({ day = 1, slotIdx = 1, size = 50, schedule = [null, null, null, null] }) {
  const cx = size / 2, cy = size / 2;
  const rOuter = size / 2 - 1.5, rInner = rOuter - 5, rHand = rInner - 3, rCenter = size * 0.22;
  const handHour = slotIdx * 6 + 3;
  function ang(h) { return (h / 24) * Math.PI * 2 - Math.PI / 2; }
  function xy(h, r) { const a = ang(h); return [cx + Math.cos(a) * r, cy + Math.sin(a) * r]; }
  const slotColors = ['#3a4a6a', '#b8632a', '#9a7d2a', '#355e7d'];
  return (
    <svg className="daydial" viewBox={`0 0 ${size} ${size}`} style={{ width: size, height: size }}>
      <circle cx={cx} cy={cy} r={rOuter} fill="var(--paper-light)" stroke="var(--ink)" strokeWidth="1.2" />
      {[0, 1, 2, 3].map(i => {
        const h0 = i * 6, h1 = (i + 1) * 6;
        const [x0, y0] = xy(h0, rInner), [x1, y1] = xy(h1, rInner);
        const isNow = i === slotIdx, done = !!schedule[i];
        let fill = 'transparent', fo = 0, stroke = 'var(--ink-ghost)', sw = 0.5, dash = '2 3';
        if (done) { fill = slotColors[i]; fo = 0.3; stroke = slotColors[i]; sw = 1; dash = 'none'; }
        else if (isNow) { fill = 'var(--stamp-amber)'; fo = 0.16; stroke = 'var(--stamp-amber)'; sw = 1.2; dash = 'none'; }
        return <path key={i} d={`M ${cx} ${cy} L ${x0} ${y0} A ${rInner} ${rInner} 0 0 1 ${x1} ${y1} Z`}
          fill={fill} fillOpacity={fo} stroke={stroke} strokeWidth={sw} strokeDasharray={dash} />;
      })}
      {Array.from({ length: 24 }).map((_, h) => {
        const major = h % 6 === 0; const [x1, y1] = xy(h, rOuter); const [x2, y2] = xy(h, major ? rOuter - 3.5 : rOuter - 2);
        return <line key={h} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--ink)" strokeWidth={major ? 0.9 : 0.4} />;
      })}
      <g transform={`rotate(${(handHour / 24) * 360} ${cx} ${cy})`}>
        <line x1={cx} y1={cy} x2={cx} y2={cy - rHand} stroke="var(--ink)" strokeWidth="1.4" strokeLinecap="round" />
      </g>
      <circle cx={cx} cy={cy} r={rCenter} fill="var(--paper)" stroke="var(--ink)" strokeWidth="0.9" />
      <text x={cx} y={cy + size * 0.07} textAnchor="middle" fontSize={size * 0.24} fill="var(--ink)"
        fontFamily="IM Fell English SC, serif" fontWeight="600">{String(day).padStart(2, '0')}</text>
    </svg>
  );
}

// ---------- meters ----------
function Meter({ value = 0, max = 100, segs = 14, tone = 'on' }) {
  const filled = Math.round((value / max) * segs);
  return (
    <div className="meter">
      {Array.from({ length: segs }).map((_, i) =>
        <div key={i} className={'meter-seg' + (i < filled ? ' ' + tone : '')} />)}
    </div>
  );
}
function StatLine({ name, value, tag, tone = 'on', segs = 14 }) {
  return (
    <div className="statline">
      <span className="nm">{name}</span>
      <Meter value={value} segs={segs} tone={tone} />
      <span className="vv">{value}</span>
      {tag && <span className="tag">{tag}</span>}
    </div>
  );
}

// ---------- the Aetheric Wheel ----------
// treatment: 'classic' (Direction A) · 'hero' (Direction B) · 'compact' (Direction C)
function AetherWheel({ size = 300, treatment = 'classic', values = {}, ontime = [], showSlotArc = false, activeSlot = 1 }) {
  const cx = size / 2, cy = size / 2;
  const ringR = treatment === 'hero' ? size * 0.40 : size * 0.385;
  const moteSize = treatment === 'hero' ? size * 0.30 : size * 0.22;
  const glowSize = moteSize * 2.1;

  // node positions, clockwise from top
  const nodes = SH_RING.map((id, i) => {
    const theta = (i / 8) * Math.PI * 2;          // 0 = top, clockwise
    const x = cx + Math.sin(theta) * ringR;
    const y = cy - Math.cos(theta) * ringR;
    return { id, x, y, i };
  });

  // slot → which two home elements sit "awake": Morning = fire, earth
  const SLOT_HOME = [['ice', 'holy'], ['fire', 'earth'], ['lightning', 'wind'], ['water', 'nature']];
  const homeNow = SLOT_HOME[activeSlot] || [];

  // arc highlight for the active time-of-day (between the two home elements)
  function arcPath() {
    const idxs = homeNow.map(h => SH_RING.indexOf(h)).filter(i => i >= 0).sort((a, b) => a - b);
    if (idxs.length < 2) return null;
    const r = ringR;
    const a0 = (idxs[0] / 8) * Math.PI * 2 - Math.PI / 2;
    const a1 = (idxs[1] / 8) * Math.PI * 2 - Math.PI / 2;
    const p0 = [cx + Math.cos(a0) * r, cy + Math.sin(a0) * r];
    const p1 = [cx + Math.cos(a1) * r, cy + Math.sin(a1) * r];
    return `M ${p0[0]} ${p0[1]} A ${r} ${r} 0 0 1 ${p1[0]} ${p1[1]}`;
  }

  return (
    <div className="wheel-wrap" style={{ width: size, height: size }}>
      <svg viewBox={`0 0 ${size} ${size}`} style={{ width: size, height: size, position: 'absolute', inset: 0 }}>
        {/* faint guide ring */}
        <circle cx={cx} cy={cy} r={ringR} fill="none" stroke="var(--ink-ghost)" strokeWidth="1" strokeDasharray="2 4" />
        {treatment !== 'compact' && (
          <circle cx={cx} cy={cy} r={ringR * 0.62} fill="none" stroke="var(--ink-trace)" strokeWidth="1" />
        )}
        {/* spokes from center to each node */}
        {nodes.map(n => (
          <line key={n.id} x1={cx} y1={cy} x2={n.x} y2={n.y}
            stroke={SH_UNLOCKED[n.id] ? 'var(--ink-ghost)' : 'var(--ink-trace)'}
            strokeWidth="0.8" strokeDasharray="2 3" />
        ))}
        {/* leak-ring direction arc (hero only): faint clockwise arrows hint the leak flow */}
        {treatment === 'hero' && (
          <circle cx={cx} cy={cy} r={ringR} fill="none" stroke="var(--stamp-amber)" strokeOpacity="0.18" strokeWidth="6" />
        )}
        {/* active time-of-day arc */}
        {showSlotArc && arcPath() && (
          <path d={arcPath()} fill="none" stroke="var(--stamp-amber)" strokeWidth="3.5" strokeLinecap="round" strokeOpacity="0.7" />
        )}
      </svg>

      {/* center mote */}
      <div className="wheel-center">
        <div className="mote-glow" style={{ width: glowSize, height: glowSize }} />
        <img className="mote" src="assets/drift-mote.png" alt="" style={{ width: moteSize, height: moteSize }} />
        {treatment !== 'compact' && <div className="mname">Drift-Mote</div>}
      </div>

      {/* element nodes */}
      {nodes.map(n => {
        const el = SH_EL[n.id];
        const unlocked = SH_UNLOCKED[n.id];
        const isOnTime = ontime.includes(n.id);
        return (
          <div key={n.id}
            className={'wheel-node' + (unlocked ? '' : ' sealed') + (isOnTime ? ' ontime' : '')}
            style={{ left: n.x, top: n.y, color: unlocked ? el.color : 'var(--ink-ghost)' }}>
            <div className="chip" style={unlocked ? { boxShadow: isOnTime ? '0 0 0 3px rgba(184,99,42,0.25)' : 'none' } : {}}>
              {unlocked
                ? <img className="drop-white" src={el.icon} alt="" />
                : <span style={{ fontSize: 14 }}>{el.glyph}</span>}
            </div>
            {unlocked
              ? <><span className="wn">{el.name}</span><span className="wv">{values[n.id] ?? 0}</span></>
              : <span className="wn">Sealed</span>}
          </div>
        );
      })}
    </div>
  );
}

// ---------- bottom tab bar ----------
const SH_TAB_ICONS = {
  raise: <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="10" cy="10" r="3.2"/><path d="M10 1v3M10 16v3M1 10h3M16 10h3M3.6 3.6l2 2M14.4 14.4l2 2M16.4 3.6l-2 2M5.6 14.4l-2 2"/></svg>,
  atlas: <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M2 4.5l5-2 6 2 5-2v13l-5 2-6-2-5 2z"/><path d="M7 2.5v13M13 4.5v13"/></svg>,
  expedition: <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M10 1.5l2.4 5 5.6.6-4.2 3.7 1.3 5.6L10 19l-5.1 2.4 1.3-5.6L2 9.1l5.6-.6z" transform="scale(0.85) translate(1.6 0)"/></svg>,
  codex: <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M3 3h6a2 2 0 012 2v12a2 2 0 00-2-2H3zM17 3h-6a2 2 0 00-2 2v12a2 2 0 012-2h6z"/></svg>,
};
function TabBar({ active = 'raise' }) {
  const tabs = [['raise', 'Raise'], ['atlas', 'Atlas'], ['expedition', 'Field'], ['codex', 'Codex']];
  return (
    <div className="tabbar">
      {tabs.map(([id, label]) => (
        <div key={id} className={'tab' + (id === active ? ' active' : '')}>
          <span className="ti">{SH_TAB_ICONS[id]}</span>
          <span>{label}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { SH_EL, SH_RING, SH_UNLOCKED, AndroidStatus, MiniDayDial, Meter, StatLine, AetherWheel, TabBar });
