// Mental palate cleanser — 3-min guided routine to transition between
// big tasks of different energy types. Lives at the top of the cockpit.
//
// Phases (60s each):
//   1. PARK    — capture where you left off (one line → Brain zips)
//   2. RESET   — body off-screen, 4 box-breaths (4-4-4-4)
//   3. AIM     — pick next priority, ideally of different "energy"

const PHASE_LEN = 60; // seconds per phase
const TOTAL = PHASE_LEN * 3;

// Rough heuristic mapping priority categories → energy buckets so we can
// suggest something of a DIFFERENT energy than what was just touched.
// Pulled from CATEGORIES (set in components/categories.jsx).
const ENERGY_OF = (tag) => (CATEGORIES[tag] || CATEGORIES.ops).energy;
const ENERGY_LABEL = (energy) => {
  const map = {
    'social-deep': 'social · deep',
    'social-warm': 'social · warm',
    'analytical':  'analytical',
    'creative':    'creative',
    'admin':       'admin · structural',
    'restorative': 'restorative',
  };
  return map[energy] || energy;
};

function Cleanser() {
  const { state, addBrainItem, startBurst, bumpCleanseStreak } = useStore();
  const [active, setActive] = React.useState(false);
  const [elapsed, setElapsed] = React.useState(0);
  const [park, setPark] = React.useState('');
  const [breath, setBreath] = React.useState('in'); // in | hold-in | out | hold-out
  const parkSavedRef = React.useRef(false);

  // 1Hz tick
  React.useEffect(() => {
    if (!active) return;
    const id = setInterval(() => setElapsed((e) => e + 1), 1000);
    return () => clearInterval(id);
  }, [active]);

  // box-breath cycle: 4s in, 4s hold, 4s out, 4s hold — driven by elapsed
  React.useEffect(() => {
    if (!active) return;
    const inPhase = phaseIndex(elapsed) === 1;
    if (!inPhase) return;
    const sec = elapsed - PHASE_LEN; // 0..60 within phase 2
    const slot = sec % 16;
    if      (slot < 4)  setBreath('in');
    else if (slot < 8)  setBreath('hold-in');
    else if (slot < 12) setBreath('out');
    else                setBreath('hold-out');
  }, [elapsed, active]);

  // when crossing into phase 3 OR when ending, save the park note (once)
  React.useEffect(() => {
    if (!active) return;
    if (elapsed >= PHASE_LEN && !parkSavedRef.current && park.trim()) {
      addBrainItem(`📍 Left off: ${park.trim()}`, 'dump');
      parkSavedRef.current = true;
    }
  }, [elapsed, active, park, addBrainItem]);

  // auto-end at 3:00
  React.useEffect(() => {
    if (active && elapsed >= TOTAL) {
      // optional: chime here
      bumpCleanseStreak();
    }
  }, [elapsed, active, bumpCleanseStreak]);

  const start = () => {
    setActive(true);
    setElapsed(0);
    setPark('');
    parkSavedRef.current = false;
  };
  const end = () => {
    if (park.trim() && !parkSavedRef.current) {
      addBrainItem(`📍 Left off: ${park.trim()}`, 'dump');
      parkSavedRef.current = true;
    }
    setActive(false);
    setElapsed(0);
  };

  if (!active) {
    return (
      <div className="mc-cleanse idle">
        <span className="mc-cleanse-idle-ico"><Icons.Refresh size={15} sw={2.25}/></span>
        <div className="mc-cleanse-idle-body">
          <span className="h">Palate cleanser</span>
          <span className="s">Just finished something? 3 minutes to transition.</span>
        </div>
        <span className="mc-cleanse-idle-streak">
          streak <b>{state.cleanseStreak || 0}</b>
        </span>
        <button className="mc-cleanse-start" onClick={start}>
          <Icons.Play size={11}/> 3:00 start
        </button>
      </div>
    );
  }

  const remaining = Math.max(0, TOTAL - elapsed);
  const m = Math.floor(remaining / 60);
  const s = remaining % 60;
  const idx = phaseIndex(elapsed);
  const phaseElapsed = elapsed - idx * PHASE_LEN;
  const phasePct = Math.min(100, (phaseElapsed / PHASE_LEN) * 100);
  const phaseNames = ['Park it', 'Reset', 'Aim'];

  return (
    <div className="mc-cleanse active">
      <div className="mc-cleanse-hd">
        <div className="lbl">
          <span className="dot"/> palate cleanser · phase {idx + 1}/3 · {phaseNames[idx]}
        </div>
        <div className="right">
          <div className="time">{String(m).padStart(2, '0')}:{String(s).padStart(2, '0')}</div>
          <button className="x" onClick={end} title="End early"><Icons.X size={13}/></button>
        </div>
      </div>

      <div className="mc-cleanse-track">
        {[0, 1, 2].map((i) => {
          const segPct = i < idx ? 100 : i === idx ? phasePct : 0;
          return (
            <div key={i} className={`seg ${i < idx ? 'done' : ''} ${i === idx ? 'active' : ''}`}>
              <span>0{i + 1} · {phaseNames[i]}</span>
              <span className="bar"><i style={{ width: `${segPct}%` }}/></span>
            </div>
          );
        })}
      </div>

      <div className="mc-cleanse-stage">
        {idx === 0 && <PhasePark   park={park} setPark={setPark} onNext={() => setElapsed(PHASE_LEN)}/>}
        {idx === 1 && <PhaseReset  breath={breath} onNext={() => setElapsed(PHASE_LEN * 2)}/>}
        {idx === 2 && <PhaseAim    onPick={(p) => { startBurst(p.id, null, state.burst.length); end(); }}
                                   onSkip={end} onDone={end}/>}
        {elapsed >= TOTAL && (
          <PhaseDone onClose={end} onPick={(p) => { startBurst(p.id, null, state.burst.length); end(); }}/>
        )}
      </div>
    </div>
  );
}

function phaseIndex(elapsed) {
  return Math.min(2, Math.floor(elapsed / PHASE_LEN));
}

// ── Phase 1: Park it ────────────────────────────────────────────
function PhasePark({ park, setPark, onNext }) {
  return (
    <>
      <div className="body">
        <h3>Where did you just leave off?</h3>
        <p>One line. Not a status report. Just enough so future-you can pick it back up. Saves to Brain&nbsp;zips automatically.</p>
        <textarea
          rows={3}
          autoFocus
          value={park}
          onChange={(e) => setPark(e.target.value)}
          placeholder="e.g. Stuck on traction slide — numbers are right, story isn't. Come back fresh."
        />
        <div className="mc-cleanse-actions">
          <button className="mc-cleanse-btn primary" onClick={onNext}>
            Parked → Reset <Icons.ArrowR size={12}/>
          </button>
          <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)' }}>
            or wait — phase auto-advances at 1:00
          </span>
        </div>
      </div>
      <div className="visual">
        <svg width="160" height="160" viewBox="0 0 160 160" style={{ opacity: 0.5 }}>
          <defs>
            <linearGradient id="park-g" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#5d6dee"/>
              <stop offset="100%" stopColor="#ec33fa"/>
            </linearGradient>
          </defs>
          <rect x="40" y="50" width="80" height="60" rx="8" fill="none" stroke="url(#park-g)" strokeWidth="1.5"/>
          <path d="M55 70h50M55 80h40M55 90h45" stroke="url(#park-g)" strokeWidth="1.5" strokeLinecap="round"/>
          <circle cx="115" cy="45" r="6" fill="#e412f1"/>
        </svg>
      </div>
    </>
  );
}

// ── Phase 2: Reset (box-breath) ─────────────────────────────────
function PhaseReset({ breath, onNext }) {
  const label = { 'in': 'breathe in', 'hold-in': 'hold', 'out': 'breathe out', 'hold-out': 'hold' }[breath];
  return (
    <>
      <div className="body">
        <h3>Eyes off the screen.</h3>
        <p>Stand if you can. Look at something far away — out the window, across the room. Follow the breath: 4 in, 4 hold, 4 out, 4 hold.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 6, fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>
          <div>· Unclench jaw</div>
          <div>· Drop shoulders</div>
          <div>· Drink water</div>
        </div>
        <div className="mc-cleanse-actions" style={{ marginTop: 8 }}>
          <button className="mc-cleanse-btn" onClick={onNext}>
            Reset done → Aim <Icons.ArrowR size={12}/>
          </button>
        </div>
      </div>
      <div className="visual">
        <div className={`mc-breathe ${breath}`}>
          <span className="mc-breathe-label">{label}</span>
        </div>
      </div>
    </>
  );
}

// ── Phase 3: Aim ────────────────────────────────────────────────
function PhaseAim({ onPick, onSkip }) {
  const { state } = useStore();
  const lastId = state.lastBurstPriorityId;
  const lastEnergy = lastId
    ? ENERGY_OF(state.priorities.find((p) => p.id === lastId)?.tag)
    : null;

  const choices = state.priorities.filter((p) => !p.done).slice(0, 4);

  return (
    <>
      <div className="body">
        <h3>Different energy now.</h3>
        <p>
          {lastEnergy
            ? <>You were in <b style={{ color: 'var(--magenta-300)' }}>{ENERGY_LABEL(lastEnergy)}</b> mode. Pick something that uses a different part of your brain — the contrast is the recovery.</>
            : <>Pick what's next. Tapping starts a burst.</>}
        </p>
        <div style={{ marginTop: 6 }}>
          <button className="mc-cleanse-btn" onClick={onSkip}>
            Not now — just close
          </button>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div className="mc-aim-grid">
          {choices.map((p, i) => {
            const energy = ENERGY_OF(p.tag);
            const isDifferent = lastEnergy && energy !== lastEnergy;
            const isLast = lastId === p.id;
            return (
              <button key={p.id}
                className={`mc-aim-chip ${isDifferent ? 'different' : ''}`}
                onClick={() => onPick(p)}>
                <span className="num">{i + 1}</span>
                <span className="ttl">{p.title}</span>
                <span className="energy">{isLast ? 'just left' : ENERGY_LABEL(energy)}</span>
              </button>
            );
          })}
        </div>
      </div>
    </>
  );
}

// ── Done state (shown if timer naturally runs out on phase 3) ───
function PhaseDone({ onClose, onPick }) {
  const { state } = useStore();
  return (
    <>
      <div className="body">
        <h3>Cleansed. Go.</h3>
        <p>Three minutes well spent. Pick a priority above to dive in, or close this strip and roam.</p>
        <div className="mc-cleanse-actions">
          <button className="mc-cleanse-btn primary" onClick={onClose}>
            <Icons.Check size={12}/> Close
          </button>
        </div>
      </div>
      <div className="visual">
        <Icons.Sparkle size={120} style={{ color: 'var(--magenta-300)', opacity: 0.5 }}/>
      </div>
    </>
  );
}

Object.assign(window, { Cleanser });
