// screen-timer.jsx — Pomodoro + Stopwatch with task picker.
// Two modes:
//  • POMO     — 25-minute focus / 5-minute break cycle, auto-switches phase
//  • STOPWATCH — pure count-up
// Task picker supports A (simple) / B (subtasks) / C (progress) tasks.
// Selecting a B/C task can drill into a subtask. The selected target's
// label is shown above the dial.

const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

const POMO_FOCUS_SEC = 25 * 60;
const POMO_BREAK_SEC = 5 * 60;

function ScreenTimer({ state, onAbort, onComplete }) {
  const { tasks = [], categories = [], activeTask, activeCategory } = state;

  const [timerMode, setTimerMode] = useStateT('pomo');         // 'pomo' | 'stopwatch'
  const [phase, setPhase] = useStateT('focus');                // 'focus' | 'break'
  const [elapsed, setElapsed] = useStateT(state.elapsedSec || 0);
  const [running, setRunning] = useStateT(true);
  const [completedRounds, setCompletedRounds] = useStateT(0);
  const [picked, setPicked] = useStateT(() => ({
    parent: activeTask || null,
    sub: null,
  }));
  const [pickerOpen, setPickerOpen] = useStateT(false);

  // Sync picked.parent whenever activeTask changes (e.g. starting a different task or clearing for focus mode)
  useEffectT(() => {
    setPicked({ parent: activeTask || null, sub: null });
  }, [activeTask ? activeTask.id : null]);

  const isPomo = timerMode === 'pomo';
  const targetSec = phase === 'focus' ? POMO_FOCUS_SEC : POMO_BREAK_SEC;

  // Tick
  useEffectT(() => {
    if (!running) return;
    const id = setInterval(() => {
      setElapsed(e => {
        if (!isPomo) return e + 1;
        const n = e + 1;
        if (n >= targetSec) {
          // auto-switch phase
          if (phase === 'focus') setCompletedRounds(r => r + 1);
          setPhase(p => (p === 'focus' ? 'break' : 'focus'));
          return 0;
        }
        return n;
      });
    }, 1000);
    return () => clearInterval(id);
  }, [running, isPomo, targetSec, phase]);

  // Reset elapsed on mode change
  useEffectT(() => { setElapsed(0); setPhase('focus'); }, [timerMode]);

  const remaining = isPomo ? Math.max(0, targetSec - elapsed) : elapsed;
  const p = isPomo ? elapsed / targetSec : (elapsed % 3600) / 3600;
  const hh = Math.floor(remaining / 3600);
  const mm = Math.floor((remaining % 3600) / 60);
  const ss = remaining % 60;

  // Resolve display label for the selected target
  const lang = (typeof window !== 'undefined' && window.__witnessLang) || 'en';
  const targetLabel = picked.sub
    ? `${getTitle(picked.parent)} · ${getTitle(picked.sub)}`
    : (picked.parent ? getTitle(picked.parent) : (lang === 'zh' ? '專注' : 'Focus'));
  const targetCategory = picked.parent
    ? categories.find(c => c.id === picked.parent.category)
    : null;
  const categoryLabel = targetCategory
    ? ((targetCategory.label && targetCategory.label[lang]) || targetCategory.label || targetCategory.id)
    : '';

  return (
    <div style={{
      width: '100%', height: '100%',
      background: `radial-gradient(80% 60% at 50% 40%, #14151a 0%, ${W.void} 75%, #000 100%)`,
      color: W.textHi, display: 'flex', flexDirection: 'column',
      fontFamily: W.mono, position: 'relative', overflow: 'hidden',
    }}>
      {/* hairline grain */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: hairlineMetal({ base: 'transparent', intensity: 0.35, density: 0.5 }),
        opacity: 0.7, mixBlendMode: 'screen',
      }} />

      <WStatusBar time="04:41" />

      {/* Header — X left, Pomo/Stopwatch centered */}
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: '6px 18px 18px',
        position: 'relative',
      }}>
        <button onClick={onAbort} style={{
          border: 0, background: 'transparent', cursor: 'pointer', padding: 6,
          color: 'rgba(232,230,224,0.45)',
          transition: 'color .2s', flexShrink: 0,
        }}
        onMouseEnter={(e) => e.currentTarget.style.color = W.textHi}
        onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(232,230,224,0.45)'}
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <line x1="3.5" y1="3.5" x2="12.5" y2="12.5" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round"/>
            <line x1="12.5" y1="3.5" x2="3.5" y2="12.5" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round"/>
          </svg>
        </button>

        {/* Centered toggle — absolute so it doesn't shift with X */}
        <div style={{ position: 'absolute', left: 0, right: 0, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
          <div style={{ pointerEvents: 'auto' }}>
            <TimerModeToggle mode={timerMode} onChange={setTimerMode} />
          </div>
        </div>
      </div>

      {/* Task chip — just the title, no category. Tap to open picker. */}
      <div style={{ padding: '4px 22px 6px', display: 'flex', justifyContent: 'center' }}>
        <button onClick={() => setPickerOpen(true)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 10,
          padding: '7px 18px',
          background: 'transparent',
          border: 'none',
          borderRadius: 9999, cursor: 'pointer',
          maxWidth: '85%',
        }}>
          <span style={{
            fontFamily: W.display, fontSize: 13.5, fontWeight: 400,
            color: picked.parent ? W.textHi : W.textLo,
            letterSpacing: '0.005em',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            maxWidth: 240,
          }}>{targetLabel}</span>
          <svg width="8" height="5" viewBox="0 0 8 5" style={{ flexShrink: 0 }}>
            <path d="M1 1l3 3 3-3" stroke={W.textLo} strokeWidth="1.1" fill="none" strokeLinecap="round"/>
          </svg>
        </button>
      </div>

      {/* Center: monolithic dial */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', padding: '0 28px' }}>
        <div style={{ position: 'relative', width: 280, height: 280, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {/* Dial */}
          <svg width="280" height="280" viewBox="0 0 280 280" style={{ position: 'absolute', inset: 0 }}>
            <defs>
              <linearGradient id="silverArc" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={W.gradHi} />
                <stop offset="55%" stopColor={W.gradMid} />
                <stop offset="100%" stopColor={W.accentDk} />
              </linearGradient>
            </defs>
            <circle cx="140" cy="140" r="128" fill="none" stroke="#06070a" strokeWidth="3" />
            {/* tick marks */}
            {Array.from({ length: 60 }).map((_, i) => {
              const a = (i / 60) * Math.PI * 2 - Math.PI / 2;
              const r1 = i % 5 === 0 ? 116 : 120;
              const r2 = 124;
              const x1 = 140 + Math.cos(a) * r1, y1 = 140 + Math.sin(a) * r1;
              const x2 = 140 + Math.cos(a) * r2, y2 = 140 + Math.sin(a) * r2;
              return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={i % 5 === 0 ? W.textLo : W.textXLo} strokeWidth={i % 5 === 0 ? 1.2 : 0.6} />;
            })}
            <circle cx="140" cy="140" r="128" fill="none"
              stroke="url(#silverArc)" strokeWidth="3"
              strokeDasharray={`${2 * Math.PI * 128 * Math.min(p, 1)} ${2 * Math.PI * 128}`}
              strokeDashoffset={0}
              transform="rotate(-90 140 140)"
              style={{ filter: `drop-shadow(0 0 6px rgba(${W.midRGB},0.35))` }}
            />
          </svg>

          {/* Breathing aura */}
          <div style={{
            position: 'absolute', width: 220, height: 220,
            background: `radial-gradient(circle, rgba(${W.midRGB},0.08) 0%, transparent 65%)`,
            animation: 'witness-breathe 4.5s ease-in-out infinite',
          }} />

          {/* Numbers */}
          <div style={{ position: 'relative', textAlign: 'center' }}>
            <div style={{
              fontFamily: W.mono, fontWeight: 200, fontSize: 68, lineHeight: 1,
              color: W.textHi, letterSpacing: '-0.04em', fontVariantNumeric: 'tabular-nums',
              ...etched(),
            }}>
              {hh > 0 ? `${String(hh)}:` : ''}{String(mm).padStart(2, '0')}
              <span style={{ color: W.accentHi }}>:</span>
              {String(ss).padStart(2, '0')}
            </div>
          </div>
        </div>
      </div>

      {/* Bottom controls */}
      <div style={{ padding: '8px 22px 30px' }}>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
          {running ? (
            <WCapsule variant="ghost" size="md" onClick={() => setRunning(false)}>{t('pause')}</WCapsule>
          ) : (
            <WCapsule variant="primary" size="lg" onClick={() => setRunning(true)}>{t('resume')}</WCapsule>
          )}
          {!isPomo && elapsed > 0 && (
            <WCapsule variant="primary" size="md" onClick={() => onComplete && onComplete(elapsed)}>
              {t('save_and_log')}
            </WCapsule>
          )}
          {isPomo && (
            <WCapsule variant="ghost" size="md" onClick={() => { setElapsed(0); setRunning(true); }}>
              {t('skip')}
            </WCapsule>
          )}
        </div>
      </div>

      {/* Picker sheet */}
      <TaskPickerSheet
        open={pickerOpen}
        onClose={() => setPickerOpen(false)}
        tasks={tasks}
        categories={categories}
        currentId={picked.parent && picked.parent.id}
        currentSubId={picked.sub && picked.sub.id}
        onPick={(parent, sub) => { setPicked({ parent: parent || null, sub: sub || null }); setPickerOpen(false); setElapsed(0); setRunning(true); }}
      />
    </div>
  );
}

// Plain English/zh title for a task or subtask
function getTitle(node) {
  if (!node) return '';
  return node.title || '';
}

// ─────────────────────────────────────────────────────────────
// TimerModeToggle — segmented control style (like reference image).
function TimerModeToggle({ mode = 'pomo', onChange }) {
  return (
    <div style={{
      display: 'inline-flex',
      background: 'rgba(255,255,255,0.07)',
      border: '0.5px solid rgba(255,255,255,0.12)',
      borderRadius: 9999,
      padding: 3,
      gap: 2,
    }}>
      {['pomo', 'stopwatch'].map(k => {
        const on = mode === k;
        return (
          <button key={k} onClick={() => onChange(k)} style={{
            padding: '6px 18px',
            border: 0,
            background: on ? 'rgba(255,255,255,0.13)' : 'transparent',
            borderRadius: 9999, cursor: 'pointer',
            fontFamily: W.display, fontSize: 13, fontWeight: on ? 600 : 400,
            letterSpacing: '0.01em',
            color: on ? W.textHi : W.textLo,
            transition: 'background .2s, color .2s, font-weight .2s',
            boxShadow: on ? '0 1px 4px rgba(0,0,0,0.35)' : 'none',
          }}>{k === 'pomo' ? t('pomo') : t('stopwatch')}</button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TaskPickerSheet — bottom sheet showing today/overdue/next7/inbox sections.
// A/B/C task rows. B/C expand to reveal subtasks; tap a subtask to pick it.
function TaskPickerSheet({ open, onClose, tasks = [], categories = [], currentId, currentSubId, onPick }) {
  const [q, setQ] = useStateT('');
  const lang = (typeof window !== 'undefined' && window.__witnessLang) || 'en';

  const norm = (s) => (s || '').toLowerCase();
  const matches = (task) => !q || norm(task.title).includes(norm(q));

  const buckets = [
    { id: 'today',   label: t('cat_today'),   tasks: tasks.filter(x => x.day === 'today'   && matches(x)) },
    { id: 'overdue', label: t('cat_overdue'), tasks: tasks.filter(x => x.day === 'overdue' && matches(x)) },
    { id: 'next7',   label: t('cat_next7'),   tasks: tasks.filter(x => x.day === 'next7'   && matches(x)) },
  ].filter(b => b.tasks.length > 0);

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 40, pointerEvents: open ? 'auto' : 'none',
    }}>
      {/* scrim */}
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(0,0,0,0.65)',
        backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
        opacity: open ? 1 : 0, transition: 'opacity .25s',
      }} />
      {/* sheet */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        maxHeight: '78%',
        background: 'linear-gradient(180deg, rgba(20,21,26,0.97) 0%, rgba(8,9,12,0.97) 100%)',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        boxShadow: '0 -24px 60px rgba(0,0,0,0.7), inset 0 1px 0 rgba(255,255,255,0.05)',
        WebkitBackdropFilter: 'blur(20px) saturate(140%)',
        backdropFilter: 'blur(20px) saturate(140%)',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform .35s cubic-bezier(.25,.85,.3,1)',
        display: 'flex', flexDirection: 'column',
        paddingBottom: 24,
      }}>
        {/* drag handle */}
        <div onClick={onClose} style={{
          margin: '12px auto 8px',
          width: 40, height: 4, borderRadius: 4,
          background: 'rgba(255,255,255,0.18)', cursor: 'pointer',
        }} />

        {/* Header */}
        <div style={{ padding: '4px 22px 8px' }}>
          <SerialNum>{t('pick_task')}</SerialNum>
        </div>

        {/* Search */}
        <div style={{ padding: '6px 16px 10px' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '8px 12px',
            background: 'rgba(0,0,0,0.4)',
            border: '0.5px solid rgba(255,255,255,0.06)',
            borderRadius: 9999,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <circle cx="6" cy="6" r="4" stroke={W.textLo} strokeWidth="1.3"/>
              <line x1="9" y1="9" x2="12.5" y2="12.5" stroke={W.textLo} strokeWidth="1.3" strokeLinecap="round"/>
            </svg>
            <input
              value={q} onChange={(e) => setQ(e.target.value)}
              placeholder={t('search')}
              style={{
                flex: 1, background: 'transparent', border: 0, outline: 'none',
                color: W.textHi, fontFamily: W.mono, fontSize: 13,
                letterSpacing: '0.02em',
              }}
            />
          </div>
        </div>

        {/* Sections */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 16px 18px' }}>
          {/* 專注（未指定）— no task selected, just focus */}
          <div style={{ marginBottom: 14 }}>
            <div
              onClick={() => onPick(null, null)}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                background: (!currentId) ? `rgba(${W.midRGB},0.12)` : 'transparent',
                border: (!currentId) ? `0.5px solid rgba(${W.midRGB},0.45)` : '0.5px solid transparent',
                transition: 'background .15s',
              }}
              onMouseEnter={(e) => { if (currentId) e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}
              onMouseLeave={(e) => { if (currentId) e.currentTarget.style.background = 'transparent'; }}
            >
              <div style={{
                width: 16, height: 16, flexShrink: 0, borderRadius: 9999,
                background: (!currentId) ? brushedAccent({ intensity: 0.85 }) : 'transparent',
                border: (!currentId) ? 'none' : '1.5px solid rgba(232,230,224,0.28)',
                position: 'relative',
              }}>
                {(!currentId) && <div style={{ position: 'absolute', inset: 4, borderRadius: 9999, background: W.onAccent }}/>}
              </div>
              <span style={{
                fontFamily: W.mono, fontSize: 13, fontWeight: 500,
                color: (!currentId) ? W.textHi : W.text,
                letterSpacing: '0.005em',
              }}>
                {lang === 'zh' ? '專注' : 'Focus'}
              </span>
            </div>
          </div>

          {buckets.length === 0 && (
            <div style={{ padding: '24px 12px', textAlign: 'center' }}>
              <SerialNum style={{ color: W.textXLo }}>{t('no_matches')}</SerialNum>
            </div>
          )}
          {buckets.map(b => (
            <div key={b.id} style={{ marginBottom: 14 }}>
              <div style={{ padding: '6px 8px 8px' }}>
                <SerialNum style={{ color: W.textLo }}>{b.label.toUpperCase()}</SerialNum>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {b.tasks.map(task => (
                  <PickerRow key={task.id} task={task}
                    selectedId={currentId} selectedSubId={currentSubId}
                    onPick={onPick} />
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// One picker row, recursive for B/C subtask drill-in.
//
// Selectability rules (consistent with list view):
//   Type A — always selectable
//   Type B — parent selectable; subtasks also selectable
//   Type C — parent NOT selectable (no checkbox in list view either);
//             only subtasks are selectable. Clicking parent only expands.
function PickerRow({ task, onPick, selectedId, selectedSubId, depth = 0, parent = null }) {
  const [open, setOpen] = useStateT(depth === 0); // all top-level rows expanded by default
  const tp = task.type || 'A';
  const hasChildren = task.subtasks && task.subtasks.length > 0;

  // Type C parent is not selectable — only its subtasks are
  const isSelectableParent = tp !== 'C' || parent !== null;

  const isSelected = parent
    ? (selectedId === parent.id && selectedSubId === task.id)
    : (selectedId === task.id && !selectedSubId);

  const handleRowClick = () => {
    if (isSelectableParent) {
      // Select this task
      if (parent) onPick(parent, task);
      else onPick(task, null);
    }
    // For type C parent: just toggle expand
    if (hasChildren) setOpen(o => !o);
  };

  return (
    <div style={{ marginLeft: depth * 14 }}>
      <div
        onClick={handleRowClick}
        style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '10px 12px', borderRadius: 8,
          cursor: isSelectableParent ? 'pointer' : 'default',
          background: isSelected ? `rgba(${W.midRGB},0.12)` : 'transparent',
          border: isSelected ? `0.5px solid rgba(${W.midRGB},0.45)` : '0.5px solid transparent',
          transition: 'background .15s',
        }}
        onMouseEnter={(e) => { if (!isSelected && isSelectableParent) e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}
        onMouseLeave={(e) => { if (!isSelected) e.currentTarget.style.background = 'transparent'; }}
      >
        {/* Left indicator */}
        {isSelectableParent ? (
          /* Radio circle — selectable */
          <div style={{
            width: 16, height: 16, flexShrink: 0, borderRadius: 9999,
            background: isSelected ? brushedAccent({ intensity: 0.85 }) : 'transparent',
            border: isSelected ? 'none' : '1.5px solid rgba(232,230,224,0.28)',
            position: 'relative',
          }}>
            {isSelected && <div style={{ position: 'absolute', inset: 4, borderRadius: 9999, background: W.onAccent }}/>}
          </div>
        ) : (
          /* Type C parent — SubtaskGlyph, not a radio (not selectable) */
          <SubtaskGlyph small />
        )}

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: W.mono, fontSize: 13, fontWeight: 500,
            color: isSelected ? W.textHi : (isSelectableParent ? W.text : W.textLo),
            letterSpacing: '0.005em',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{task.title}</div>
        </div>

        {tp === 'C' && task.progress !== undefined && (
          <PieGlyph value={task.progress} />
        )}

        {/* Chevron for expandable rows */}
        {hasChildren && (
          <div
            onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
            style={{ padding: '4px 2px', cursor: 'pointer', flexShrink: 0 }}
          >
            <svg width="9" height="6" viewBox="0 0 9 6" style={{
              transform: open ? 'none' : 'rotate(-90deg)', transition: 'transform .2s', display: 'block',
            }}>
              <path d="M1 1l3.5 4L8 1" stroke={W.textLo} strokeWidth="1.3" fill="none" strokeLinecap="round"/>
            </svg>
          </div>
        )}
      </div>

      {hasChildren && open && task.subtasks.map(sub => (
        <PickerRow key={sub.id} task={sub} onPick={onPick} parent={task}
          selectedId={selectedId} selectedSubId={selectedSubId}
          depth={depth + 1} />
      ))}
    </div>
  );
}

Object.assign(window, { ScreenTimer });
