// Pasta Cook Timer

const PASTA_COOK_TIMES = [
  { id: 'truffle',  name: 'Truffle Mafaldine',    shape: 'Long ribbon pasta',  time: 210, tip: 'Stir gently in the first 30 seconds to prevent sticking.', img: 'https://images.unsplash.com/photo-1622973536968-3ead9e780960?w=800&q=80' },
  { id: 'squid',    name: 'Squid Ink Tagliolini', shape: 'Long thin pasta',    time: 180, tip: 'Tagliolini cooks fast — watch closely in the last 30 seconds.', img: 'https://images.unsplash.com/photo-1551183053-bf91a1d81141?w=800&q=80' },
  { id: 'rigatoni', name: 'Classic Rigatoni',      shape: 'Short ridged pasta', time: 270, tip: 'Test at 3:30 — the ridges should still have a firm bite.', img: 'https://images.unsplash.com/photo-1587740908075-9e245311e158?w=800&q=80' },
  { id: 'burrata',  name: 'Burrata & Pomodoro',    shape: 'Short fresh pasta',  time: 300, tip: 'Fresh pasta cooks faster than dried — trust the timer, not the color.', img: 'https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?w=800&q=80' },
  { id: 'pesto',    name: 'Pesto alla Genovese',   shape: 'Long thin pasta',    time: 195, tip: 'Never rinse after draining — the starch helps the pesto cling.', img: 'https://images.unsplash.com/photo-1473093226795-af9932fe5856?w=800&q=80' },
  { id: 'cacio',    name: 'Cacio e Pepe',          shape: 'Long thin pasta',    time: 210, tip: 'Reserve extra pasta water — you\'ll need it for the sauce emulsion.', img: 'https://images.unsplash.com/photo-1556761223-4c4282c73f77?w=800&q=80' },
];

function GLCookTimer({ app, go }) {
  const [phase, setPhase] = React.useState('select'); // select | active | done
  const [selected, setSelected] = React.useState(null);
  const [remaining, setRemaining] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const totalRef = React.useRef(0);

  React.useEffect(() => {
    if (phase !== 'active' || paused) return;
    const interval = setInterval(() => {
      setRemaining(r => {
        if (r <= 1) { setPhase('done'); return 0; }
        return r - 1;
      });
    }, 1000);
    return () => clearInterval(interval);
  }, [phase, paused]);

  const startTimer = (pasta) => {
    totalRef.current = pasta.time;
    setSelected(pasta);
    setRemaining(pasta.time);
    setPaused(false);
    setPhase('active');
  };

  const reset = () => {
    setPhase('select');
    setSelected(null);
    setPaused(false);
  };

  if (phase === 'done') return <CookDone pasta={selected} onReset={reset} onHome={() => go('home')} />;
  if (phase === 'active') return (
    <CookActive
      pasta={selected} remaining={remaining} total={totalRef.current}
      paused={paused} onPause={() => setPaused(p => !p)} onReset={reset}
    />
  );
  return <CookSelect onSelect={startTimer} go={go} app={app} />;
}

// ─── Screen 1: Pasta selection ───────────────────────────────────────────────

function CookSelect({ onSelect, go, app }) {
  const [chosen, setChosen] = React.useState(null);

  const fmtTime = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;

  return (
    <div style={{ width: '100%', height: '100%', background: GL.paper, display: 'flex', flexDirection: 'column' }}>
      <GLTopBar onBack={() => go('lab')} cartCount={app.cart.length} onCart={() => go('box')}
        center={
          <div style={{ textAlign: 'center' }}>
            <div className="gl-mono" style={{ fontSize: 9, letterSpacing: '0.22em', color: GL.muted }}>GUSTAI LAB</div>
            <div className="gl-display" style={{ fontSize: 13, color: GL.ink }}>PASTA TIMER</div>
          </div>
        }
      />

      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 140 }} className="gl-noscroll">
        <div style={{ padding: '20px 20px 6px' }}>
          <h1 className="gl-display" style={{ fontSize: 44, lineHeight: 0.9, margin: 0, color: GL.ink }}>
            Cook It<br/><span style={{ color: GL.teal, fontStyle: 'italic' }}>Perfect.</span>
          </h1>
          <p style={{ fontSize: 13, color: GL.muted, marginTop: 14, lineHeight: 1.6, fontWeight: 500, maxWidth: 300 }}>
            Select your pasta. We'll count down the exact time for a perfect al dente bite — every time.
          </p>
          <div style={{ height: 1, background: GL.line, marginTop: 16 }} />
        </div>

        <div style={{ padding: '10px 20px 0' }}>
          {PASTA_COOK_TIMES.map(pasta => {
            const on = chosen?.id === pasta.id;
            return (
              <button key={pasta.id} onClick={() => setChosen(pasta)}
                style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 14,
                  padding: 14, marginBottom: 10, textAlign: 'left', cursor: 'pointer',
                  border: `2px solid ${on ? GL.teal : GL.line}`,
                  background: on ? `${GL.teal}12` : '#fff',
                  boxShadow: on ? `3px 3px 0 ${GL.teal}` : 'none',
                  transition: 'border-color .15s, box-shadow .15s, background .15s',
                }}>
                {/* Radio dot */}
                <div style={{
                  width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
                  border: `2px solid ${on ? GL.teal : '#C0CACA'}`,
                  background: on ? GL.teal : '#fff',
                  display: 'grid', placeItems: 'center', transition: 'all .15s',
                }}>
                  {on && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke={GL.ink} strokeWidth="3.5" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>}
                </div>
                {/* Thumbnail */}
                <div style={{ width: 52, height: 52, borderRadius: 6, overflow: 'hidden', flexShrink: 0, background: GL.offwhite }}>
                  <img src={pasta.img} alt={pasta.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} onError={e => e.currentTarget.style.display = 'none'}/>
                </div>
                {/* Info */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="gl-display" style={{ fontSize: 13, color: GL.ink, letterSpacing: '0.03em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{pasta.name}</div>
                  <div style={{ fontSize: 11, color: GL.muted, marginTop: 2 }}>{pasta.shape}</div>
                </div>
                {/* Time badge */}
                <div style={{
                  flexShrink: 0, padding: '6px 10px', textAlign: 'center',
                  background: on ? GL.teal : GL.offwhite,
                  transition: 'background .15s',
                }}>
                  <div className="gl-mono" style={{ fontSize: 17, fontWeight: 700, color: on ? GL.ink : GL.ink, letterSpacing: '-0.01em' }}>{fmtTime(pasta.time)}</div>
                  <div style={{ fontSize: 9, fontWeight: 800, letterSpacing: '0.12em', color: on ? GL.ink : GL.muted, textTransform: 'uppercase', marginTop: 1 }}>min:sec</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Footer */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '14px 20px 28px', background: GL.paper, borderTop: `1px solid ${GL.line}` }}>
        {chosen && (
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 14px', background: GL.offwhite, marginBottom: 12, borderLeft: `3px solid ${GL.teal}` }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={GL.teal} strokeWidth="2" style={{ marginTop: 1, flexShrink: 0 }}><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>
            <span style={{ fontSize: 12, color: GL.muted, lineHeight: 1.5 }}>{chosen.tip}</span>
          </div>
        )}
        <GLButton
          variant={chosen ? 'primary' : 'outline'}
          disabled={!chosen}
          onClick={() => chosen && onSelect(chosen)}
          icon={
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
              <circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>
            </svg>
          }
        >
          {chosen ? `Start Timer — ${Math.floor(chosen.time / 60)}:${String(chosen.time % 60).padStart(2, '0')}` : 'Select a Pasta to Begin'}
        </GLButton>
      </div>
    </div>
  );
}

// ─── Screen 2: Active countdown ──────────────────────────────────────────────

function CookActive({ pasta, remaining, total, paused, onPause, onReset }) {
  const R = 130;
  const CX = 160;
  const circ = 2 * Math.PI * R;
  const progress = remaining / total;
  const dashOffset = circ * (1 - progress);
  const urgent = remaining <= 30;
  const mm = String(Math.floor(remaining / 60)).padStart(2, '0');
  const ss = String(remaining % 60).padStart(2, '0');
  const accentColor = urgent ? '#FF6B35' : GL.teal;

  return (
    <div style={{ width: '100%', height: '100%', background: GL.darkBg, display: 'flex', flexDirection: 'column' }}>
      {/* Top bar */}
      <div style={{ padding: '64px 20px 12px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <div className="gl-mono" style={{ fontSize: 9, color: GL.teal, letterSpacing: '0.24em', marginBottom: 4 }}>NOW COOKING</div>
          <div className="gl-display" style={{ fontSize: 20, color: '#fff', lineHeight: 1 }}>{pasta.name}</div>
          <div style={{ fontSize: 11, color: GL.mutedDark, marginTop: 4 }}>{pasta.shape}</div>
        </div>
        <button onClick={onReset} style={{
          padding: '8px 14px', borderRadius: 4,
          border: '1px solid rgba(255,255,255,0.18)', color: 'rgba(255,255,255,0.45)',
          fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase',
        }}>Cancel</button>
      </div>

      {/* Ring */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
        <svg width="320" height="320" style={{ transform: 'rotate(-90deg)', overflow: 'visible' }}>
          {/* track */}
          <circle cx={CX} cy={CX} r={R} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="8"/>
          {/* progress */}
          <circle cx={CX} cy={CX} r={R} fill="none"
            stroke={accentColor} strokeWidth="8"
            strokeDasharray={circ}
            strokeDashoffset={dashOffset}
            strokeLinecap="round"
            style={{ transition: paused ? 'none' : 'stroke-dashoffset 1s linear, stroke .4s ease' }}
          />
          {/* dot at leading edge */}
          <circle
            cx={CX + R * Math.cos(-Math.PI / 2 + (1 - progress) * 2 * Math.PI)}
            cy={CX + R * Math.sin(-Math.PI / 2 + (1 - progress) * 2 * Math.PI)}
            r="6" fill={accentColor}
            style={{ transition: paused ? 'none' : 'cx 1s linear, cy 1s linear, fill .4s ease' }}
          />
        </svg>
        {/* Center display — absolutely positioned over the SVG */}
        <div style={{ position: 'absolute', textAlign: 'center', pointerEvents: 'none' }}>
          <div className="gl-mono" style={{
            fontSize: 58, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1,
            color: urgent ? '#FF6B35' : '#fff',
            transition: 'color .4s ease',
            animation: urgent && !paused ? 'gl-pulse 1s ease-in-out infinite' : 'none',
          }}>{mm}:{ss}</div>
          <div style={{
            fontSize: 10, fontWeight: 700, letterSpacing: '0.22em', textTransform: 'uppercase', marginTop: 10,
            color: paused ? GL.teal : urgent ? '#FF6B35' : 'rgba(255,255,255,0.35)',
            transition: 'color .4s',
          }}>
            {paused ? '— Paused —' : urgent ? 'Almost done!' : 'remaining'}
          </div>
        </div>
      </div>

      {/* Bottom controls */}
      <div style={{ padding: '0 20px 32px' }}>
        <div style={{ padding: '14px 16px', borderLeft: `2px solid ${GL.teal}`, background: 'rgba(89,223,232,0.06)', marginBottom: 18 }}>
          <div className="gl-kicker" style={{ color: GL.teal, marginBottom: 4 }}>Lab Tip</div>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)', lineHeight: 1.55 }}>{pasta.tip}</div>
        </div>
        <button onClick={onPause} style={{
          width: '100%', height: 58, borderRadius: 4,
          background: paused ? GL.teal : 'rgba(255,255,255,0.07)',
          color: paused ? GL.ink : '#fff',
          border: `1.5px solid ${paused ? GL.teal : 'rgba(255,255,255,0.15)'}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          fontSize: 13, fontWeight: 800, letterSpacing: '0.18em', textTransform: 'uppercase',
          transition: 'all .2s', cursor: 'pointer',
        }}>
          {paused
            ? <><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9V3z"/></svg>Resume</>
            : <><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="3" width="4" height="18" rx="1"/><rect x="15" y="3" width="4" height="18" rx="1"/></svg>Pause</>
          }
        </button>
      </div>
    </div>
  );
}

// ─── Screen 3: Done ───────────────────────────────────────────────────────────

function CookDone({ pasta, onReset, onHome }) {
  return (
    <div style={{ width: '100%', height: '100%', background: GL.teal, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 28px', textAlign: 'center' }}>
      {/* Check circle */}
      <div className="gl-slide-up" style={{
        width: 116, height: 116, borderRadius: '50%',
        border: `3px solid ${GL.ink}`,
        display: 'grid', placeItems: 'center', marginBottom: 28,
      }}>
        <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke={GL.ink} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 6L9 17l-5-5"/>
        </svg>
      </div>

      <h1 className="gl-display" style={{ fontSize: 56, lineHeight: 0.88, color: GL.ink, margin: '0 0 10px' }}>
        Drain<br/>Now!
      </h1>
      <div className="gl-display" style={{ fontSize: 17, color: 'rgba(10,10,10,0.6)', marginBottom: 32 }}>
        {pasta.name} is ready.
      </div>

      <div style={{ background: 'rgba(10,10,10,0.1)', padding: '16px 18px', borderRadius: 8, marginBottom: 36, width: '100%', textAlign: 'left' }}>
        <div className="gl-kicker" style={{ color: GL.ink, opacity: 0.55, marginBottom: 6 }}>Before you drain</div>
        <div style={{ fontSize: 13, color: GL.ink, lineHeight: 1.6, fontWeight: 500 }}>
          Reserve ½ cup of pasta water — it's the secret to a silky sauce emulsion. Don't skip it!
        </div>
      </div>

      <button onClick={onReset} style={{
        width: '100%', height: 56, background: GL.ink, color: '#fff', border: 'none', borderRadius: 4,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        fontSize: 13, fontWeight: 800, letterSpacing: '0.18em', textTransform: 'uppercase',
        marginBottom: 14, cursor: 'pointer',
      }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M1 4v6h6M23 20v-6h-6M20.5 9A9 9 0 0 0 5.3 5.3L1 10M23 14l-4.3 4.7A9 9 0 0 1 3.5 15"/></svg>
        Cook Another Pasta
      </button>
      <button onClick={onHome} style={{
        fontSize: 12, fontWeight: 700, color: GL.ink, opacity: 0.6,
        letterSpacing: '0.14em', textTransform: 'uppercase', background: 'none', border: 'none',
        cursor: 'pointer', textDecoration: 'underline',
      }}>Back to Menu</button>
    </div>
  );
}

Object.assign(window, { GLCookTimer });
