// =========================================================
// HABITS panel + MOBILE view
// =========================================================

function HabitsPanel({ T, D, habits, onToggleToday, onAddHabit }) {
  const [adding, setAdding] = useState(false);
  const [name, setName] = useState('');
  const [target, setTarget] = useState(5);
  const todayIdx = (new Date().getDay() + 6) % 7; // Mon=0

  const submit = () => {
    if (!name.trim()) return;
    onAddHabit({ name: name.trim(), target: Number(target), unit: 'x / week' });
    setName(''); setAdding(false);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{
        padding: '18px 22px 14px',
        borderBottom: `1px solid ${T.line}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div>
          <MonoLabel T={T}>HABITS ░ RECURRING</MonoLabel>
          <div style={{
            fontFamily: 'var(--sans)', fontSize: 20, color: T.fg,
            letterSpacing: 'var(--tight)', marginTop: 6, fontWeight: 'var(--hw)',
          }}>The non-negotiables</div>
        </div>
        <button
          onClick={() => setAdding(!adding)}
          style={{
            border: `1px solid ${T.line}`, background: 'transparent',
            color: T.fg2, fontFamily: 'var(--mono)', fontSize: 10,
            letterSpacing: '0.1em', padding: '5px 10px', cursor: 'pointer',
          }}
        >{adding ? '×' : '+ NEW'}</button>
      </div>

      {adding && (
        <div style={{ padding: '12px 22px', borderBottom: `1px solid ${T.line}`, background: T.panel2 }}>
          <input
            placeholder="Habit name…"
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
            style={{
              width: '100%', border: 'none', outline: 'none', background: 'transparent',
              fontFamily: 'var(--sans)', fontSize: 14, color: T.fg, padding: '6px 0',
            }}
            autoFocus
          />
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8 }}>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3, letterSpacing: '0.1em' }}>TARGET</span>
            <input
              type="number" min={1} max={7} value={target}
              onChange={(e) => setTarget(e.target.value)}
              style={{
                width: 40, border: `1px solid ${T.line}`, background: T.panel,
                color: T.fg, fontFamily: 'var(--mono)', fontSize: 12, padding: '3px 6px',
              }}
            />
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3 }}>× / week</span>
            <button
              onClick={submit}
              style={{
                marginLeft: 'auto', border: `1px solid ${T.accent}`, background: T.accent,
                color: T.panel, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.1em',
                padding: '5px 10px', cursor: 'pointer',
              }}
            >ADD ⏎</button>
          </div>
        </div>
      )}

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {habits.map((h) => {
          const hits = h.days.reduce((a,b) => a+b, 0);
          return (
            <div key={h.id} style={{
              padding: '16px 22px',
              borderBottom: `1px solid ${T.line}`,
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
                <div style={{
                  fontFamily: 'var(--sans)', fontSize: 15, color: T.fg,
                  letterSpacing: '-0.005em', fontWeight: 'var(--hw)',
                }}>{h.name}</div>
                <div style={{ flex: 1 }} />
                <div style={{
                  fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3,
                  letterSpacing: '0.08em',
                }}>{hits}/{h.target}</div>
                <div style={{
                  fontFamily: 'var(--mono)', fontSize: 11,
                  color: h.streak >= 7 ? T.accent : T.fg2,
                  letterSpacing: '0.05em',
                }}>
                  <span style={{ color: T.fg3, marginRight: 4 }}>STREAK</span>
                  {String(h.streak).padStart(2, '0')}
                </div>
              </div>
              {/* week grid */}
              <div style={{ display: 'flex', gap: 6 }}>
                {h.days.map((d, i) => {
                  const isToday = i === todayIdx;
                  return (
                    <button
                      key={i}
                      onClick={() => onToggleToday(h.id, i)}
                      title={dayDots[i]}
                      style={{
                        flex: 1, height: 28, border: `1px solid ${isToday ? T.accent : T.line}`,
                        background: d ? (isToday ? T.accent : T.fg) : 'transparent',
                        cursor: 'pointer', padding: 0,
                        fontFamily: 'var(--mono)', fontSize: 10,
                        color: d ? (isToday ? T.panel : T.panel) : T.fg3,
                        letterSpacing: '0.08em',
                        position: 'relative',
                      }}
                    >
                      {dayDots[i]}
                    </button>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---------- MOBILE ----------
function MobileView({ T, D, tasks, inbox, habits, onAddTask, onToggle, onStar, onDelete, onDeleteInbox, onAddHabit, onToggleHabitDay, onDeleteHabit, onEdit, onEditDescription, showHabits, onSetNow, onMoveBucket }) {
  const [habitForm, setHabitForm] = useState(false);
  const [habitName, setHabitName] = useState('');
  const [habitTarget, setHabitTarget] = useState(5);
  const submitHabit = () => {
    if (!habitName.trim()) return;
    onAddHabit({ name: habitName.trim(), target: Number(habitTarget) || 5, unit: 'x / week' });
    setHabitName(''); setHabitTarget(5); setHabitForm(false);
  };
  const [tab, setTab] = useState('today'); // today | inbox | habits
  const [val, setVal] = useState('');
  const now = useClock();
  const todayIdx = (new Date().getDay() + 6) % 7;

  // Today = real tasks only. Habits live in the Habits tab.
  const allActive = tasks.filter(t => !t.done);
  const nowTask = allActive.find(t => t.bucket === 'now') || null;
  const nextTasks = allActive.filter(t => t.bucket === 'next');
  const laterTasks = allActive.filter(t => t.bucket === 'later');
  const done = tasks.filter(t => t.done);

  const submit = () => {
    if (!val.trim()) return;
    onAddTask({ title: val.trim(), context: '', starred: false });
    setVal('');
  };

  const Tab = ({ id, label, count }) => (
    <button
      onClick={() => setTab(id)}
      style={{
        flex: 1, border: 'none', background: 'transparent',
        padding: '10px 0', cursor: 'pointer',
        fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.14em',
        color: tab === id ? T.fg : T.fg3,
        borderTop: `2px solid ${tab === id ? T.accent : 'transparent'}`,
        position: 'relative',
      }}
    >
      {label}
      {count != null && <span style={{ marginLeft: 6, color: T.fg3 }}>{count}</span>}
    </button>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: T.panel }}>
      {/* header */}
      <div style={{ padding: '8px 20px 16px' }}>
        <MonoLabel T={T}>{now.toLocaleDateString('en-US',{weekday:'long'}).toUpperCase()} ░ {now.toLocaleDateString('en-US',{month:'short',day:'numeric'}).toUpperCase()}</MonoLabel>
        <div style={{
          fontFamily: 'var(--sans)', fontSize: 26, color: T.fg,
          letterSpacing: 'var(--display-tight)', marginTop: 6, fontWeight: 'var(--hw)',
          lineHeight: 1.1,
        }}>
          {nowTask ? nowTask.title : nextTasks[0] ? 'Pick a Now.' : 'All clear.'}
        </div>
        <div style={{ marginTop: 6, fontFamily: 'var(--mono)', fontSize: 9, color: T.fg3, letterSpacing: '0.1em' }}>
          {nowTask ? '◉ LOCKED' : '○ NO TARGET'} ░ {nextTasks.length} NEXT ░ {laterTasks.length} LATER
        </div>
      </div>

      {/* capture */}
      <div style={{
        margin: '0 20px 12px', padding: '10px 12px',
        border: `1px solid ${T.line}`,
        display: 'flex', alignItems: 'center', gap: 10,
        background: T.panel2,
      }}>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 13, color: T.accent }}>›</span>
        <input
          placeholder="Capture anything…"
          value={val}
          onChange={(e) => setVal(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
          style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent',
            fontFamily: 'var(--sans)', fontSize: 14, color: T.fg,
          }}
        />
        <button
          onClick={submit}
          style={{
            border: 'none', background: 'transparent', color: T.fg3,
            fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.1em',
            cursor: 'pointer',
          }}
        >⏎</button>
      </div>

      {/* tabs */}
      <div style={{
        display: 'flex', borderTop: `1px solid ${T.line}`, borderBottom: `1px solid ${T.line}`,
      }}>
        <Tab id="today" label="TODAY" count={allActive.length} />
        <Tab id="inbox" label="INBOX" count={inbox.length} />
        {showHabits && <Tab id="habits" label="HABITS" />}
      </div>

      {/* content */}
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {tab === 'today' && (
          <>
            <div style={{ padding: '14px 20px 6px' }}>
              <MonoLabel T={T}>◉ NOW</MonoLabel>
            </div>
            {nowTask ? (
              <div style={{
                margin: '0 20px 4px', padding: '14px 12px',
                border: `1px solid ${T.accent}`, background: T.accentSoft,
                display: 'flex', alignItems: 'flex-start', gap: 10,
              }}>
                <button onClick={() => onToggle(nowTask.id)}
                  style={{ width: 18, height: 18, marginTop: 2, border: `1px solid ${T.accent}`, background: 'transparent', cursor: 'pointer', padding: 0, flexShrink: 0 }} />
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
                  <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: T.fg, fontWeight: 'var(--hw)' }}>{nowTask.title}</div>
                  {nowTask.description && nowTask.description.trim() && (
                    <div style={{
                      fontFamily: 'var(--sans)', fontSize: 12.5, color: T.fg2,
                      lineHeight: 1.5, whiteSpace: 'pre-wrap',
                    }}>{nowTask.description}</div>
                  )}
                </div>
                {nowTask.isHabit && <span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: T.accent, letterSpacing: '0.08em' }}>H·{nowTask.streak}</span>}
                {!nowTask.isHabit && onMoveBucket && (
                  <button
                    onClick={() => onMoveBucket(nowTask.id, 'next')}
                    aria-label="Release (move back to Next)"
                    style={{
                      border: `1px solid ${T.accent}`, background: 'transparent',
                      color: T.accent, fontFamily: 'var(--mono)', fontSize: 9,
                      letterSpacing: '0.12em', padding: '4px 8px', cursor: 'pointer',
                      flexShrink: 0,
                    }}
                  >RELEASE</button>
                )}
                {!nowTask.isHabit && onDelete && (
                  <button
                    onClick={() => onDelete(nowTask.id)}
                    aria-label="Delete task"
                    style={{
                      width: 26, height: 26, padding: 0, flexShrink: 0,
                      border: 'none', background: 'transparent', color: T.fg3,
                      fontSize: 16, lineHeight: 1, cursor: 'pointer',
                    }}
                  >×</button>
                )}
              </div>
            ) : (
              <div style={{ margin: '0 20px 4px', padding: '14px', border: `1px dashed ${T.line}`, textAlign: 'center', fontFamily: 'var(--mono)', fontSize: 9, color: T.fg3, letterSpacing: '0.12em' }}>
                ─── PICK A TARGET ───
              </div>
            )}
            <div style={{ padding: '14px 20px 6px', opacity: nowTask ? 0.55 : 1 }}>
              <MonoLabel T={T}>▸ NEXT · {nextTasks.length}</MonoLabel>
            </div>
            <div style={{ opacity: nowTask ? 0.55 : 1 }}>
              {nextTasks.map(t => (
                <MobileTaskRow key={t.id} T={T} D={D} task={t} onToggle={onToggle} onSetNow={onSetNow} onDelete={onDelete} onEditDescription={onEditDescription} />
              ))}
            </div>
            {laterTasks.length > 0 && (
              <>
                <div style={{ padding: '14px 20px 6px', opacity: 0.55 }}>
                  <MonoLabel T={T}>⇣ LATER · {laterTasks.length}</MonoLabel>
                </div>
                <div style={{ opacity: 0.55 }}>
                  {laterTasks.map(t => (
                    <MobileTaskRow key={t.id} T={T} D={D} task={t} onToggle={onToggle} onSetNow={onSetNow} onDelete={onDelete} onEditDescription={onEditDescription} />
                  ))}
                </div>
              </>
            )}
            {done.length > 0 && (
              <>
                <div style={{ padding: '18px 20px 4px' }}>
                  <MonoLabel T={T}>✓ DONE · {done.length}</MonoLabel>
                </div>
                {done.map(t => (
                  <MobileTaskRow key={t.id} T={T} D={D} task={t} onToggle={onToggle} onSetNow={onSetNow} onDelete={onDelete} onEditDescription={onEditDescription} />
                ))}
              </>
            )}
          </>
        )}
        {tab === 'inbox' && (
          <>
            <div style={{ padding: '14px 20px 6px' }}>
              <MonoLabel T={T}>UNPROCESSED · {inbox.length}</MonoLabel>
              <div style={{ fontFamily: 'var(--sans)', fontSize: 12, color: T.fg3, marginTop: 4 }}>
                Capture now. Sort later. Swipe to task.
              </div>
            </div>
            {inbox.map(it => (
              <div key={it.id} style={{
                padding: '14px 20px', borderBottom: `1px solid ${T.line}`,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{ flex: 1, fontSize: 14, color: T.fg, fontFamily: 'var(--sans)' }}>{it.title}</div>
                <button
                  onClick={() => onAddTask({ title: it.title, context: '', starred: false, fromInbox: it.id })}
                  aria-label="Promote to task"
                  style={{
                    border: `1px solid ${T.accent}`, background: 'transparent',
                    color: T.accent, fontFamily: 'var(--mono)', fontSize: 10,
                    letterSpacing: '0.08em', padding: '4px 8px', cursor: 'pointer',
                  }}
                >→</button>
                <button
                  onClick={() => onDeleteInbox && onDeleteInbox(it.id)}
                  aria-label="Delete inbox item"
                  style={{
                    width: 26, height: 26, padding: 0,
                    border: 'none', background: 'transparent', color: T.fg3,
                    fontSize: 16, lineHeight: 1, cursor: 'pointer',
                  }}
                >×</button>
              </div>
            ))}
          </>
        )}
        {tab === 'habits' && showHabits && (
          <div>
            <div style={{
              padding: '14px 20px', display: 'flex', alignItems: 'center',
              justifyContent: 'space-between', borderBottom: `1px solid ${T.line}`,
            }}>
              <MonoLabel T={T}>RECURRING · {habits.length}</MonoLabel>
              <button
                onClick={() => setHabitForm(v => !v)}
                style={{
                  border: `1px solid ${T.line}`, background: 'transparent',
                  color: T.fg2, fontFamily: 'var(--mono)', fontSize: 10,
                  letterSpacing: '0.12em', padding: '5px 10px', cursor: 'pointer',
                }}
              >{habitForm ? 'CANCEL' : '+ NEW'}</button>
            </div>

            {habitForm && (
              <div style={{ padding: '14px 20px', borderBottom: `1px solid ${T.line}`, background: T.panel2 }}>
                <input
                  placeholder="Habit name (e.g. Gym)"
                  value={habitName}
                  onChange={(e) => setHabitName(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter') submitHabit(); }}
                  autoFocus
                  style={{
                    width: '100%', padding: '10px 12px', fontSize: 14,
                    border: `1px solid ${T.line}`, outline: 'none', background: T.panel,
                    fontFamily: 'var(--sans)', color: T.fg, marginBottom: 8,
                  }}
                />
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3, letterSpacing: '0.1em' }}>TARGET</span>
                  <input
                    type="number" min="1" max="7"
                    value={habitTarget}
                    onChange={(e) => setHabitTarget(e.target.value)}
                    style={{
                      width: 50, padding: '6px 8px', fontSize: 13,
                      border: `1px solid ${T.line}`, outline: 'none', background: T.panel,
                      fontFamily: 'var(--mono)', color: T.fg, textAlign: 'center',
                    }}
                  />
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3, letterSpacing: '0.1em' }}>× / WEEK</span>
                  <div style={{ flex: 1 }} />
                  <button
                    onClick={submitHabit}
                    style={{
                      border: 'none', background: T.fg, color: T.panel,
                      fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em',
                      padding: '7px 14px', cursor: 'pointer',
                    }}
                  >ADD</button>
                </div>
              </div>
            )}

            {habits.length === 0 && !habitForm && (
              <div style={{
                padding: '40px 20px', textAlign: 'center',
                fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3, letterSpacing: '0.12em',
              }}>─── NO HABITS YET ───</div>
            )}

            {habits.map(h => {
              const hits = h.days.reduce((a,b) => a+b, 0);
              return (
                <div key={h.id} style={{ padding: '16px 20px', borderBottom: `1px solid ${T.line}` }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
                    <div style={{ fontFamily: 'var(--sans)', fontSize: 15, color: T.fg, fontWeight: 'var(--hw)' }}>{h.name}</div>
                    <div style={{ flex: 1 }} />
                    <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3 }}>{hits}/{h.target}</div>
                    <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: h.streak >= 7 ? T.accent : T.fg2 }}>
                      {h.streak}
                    </div>
                    <button
                      onClick={() => onDeleteHabit && onDeleteHabit(h.id)}
                      aria-label="Delete habit"
                      style={{
                        width: 26, height: 26, padding: 0, marginLeft: 2,
                        border: 'none', background: 'transparent', color: T.fg3,
                        fontSize: 16, lineHeight: 1, cursor: 'pointer',
                      }}
                    >×</button>
                  </div>
                  <div style={{ display: 'flex', gap: 4 }}>
                    {h.days.map((d, i) => (
                      <button
                        key={i}
                        onClick={() => onToggleHabitDay && onToggleHabitDay(h.id, i)}
                        style={{
                          flex: 1, height: 32, padding: 0,
                          border: `1px solid ${i === todayIdx ? T.accent : T.line}`,
                          background: d ? T.fg : 'transparent',
                          fontFamily: 'var(--mono)', fontSize: 9,
                          color: d ? T.panel : T.fg3,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          cursor: 'pointer',
                        }}
                      >{dayDots[i]}</button>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function MobileTaskRow({ T, D, task, onToggle, onSetNow, onDelete, onEditDescription }) {
  const [descOpen, setDescOpen] = useState(false);
  const [desc, setDesc] = useState(task.description || '');
  const hasDesc = !!(task.description && task.description.trim());
  const commitDesc = () => {
    if ((desc || '') !== (task.description || '') && onEditDescription) onEditDescription(task.id, desc);
  };
  return (
    <div style={{
      borderBottom: `1px solid ${T.line}`,
      borderLeft: task.starred ? `2px solid ${T.star}` : '2px solid transparent',
    }}>
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 20px',
    }}>
      <button
        onClick={() => onToggle(task.id)}
        style={{
          width: 18, height: 18, flexShrink: 0,
          border: `1px solid ${task.done ? T.accent : T.fg3}`,
          background: task.done ? T.accent : 'transparent',
          cursor: 'pointer', padding: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}
      >
        {task.done && (
          <svg width="10" height="10" viewBox="0 0 10 10">
            <path d="M1.5 5 L4 7.5 L8.5 2.5" stroke={T.panel} strokeWidth="1.6" fill="none" strokeLinecap="square" />
          </svg>
        )}
      </button>
      <div style={{
        flex: 1, fontFamily: 'var(--sans)', fontSize: 14,
        color: task.done ? T.done : T.fg,
        textDecoration: task.done ? 'line-through' : 'none',
      }}>{task.title}</div>
      {task.isHabit && (
        <span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: T.accent, letterSpacing: '0.08em' }}>H·{task.streak}</span>
      )}
      {task.starred && <span style={{ color: T.star, fontSize: 12 }}>★</span>}
      {task.context && !task.isHabit && (
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 9, color: T.fg3,
          letterSpacing: '0.08em', padding: '2px 6px',
          border: `1px solid ${T.line}`,
        }}>{task.context}</div>
      )}
      {!task.done && !task.isHabit && onSetNow && task.bucket !== 'now' && (
        <button
          onClick={() => onSetNow(task.id)}
          aria-label="Promote to Now"
          style={{
            border: `1px solid ${T.accent}`, background: 'transparent',
            color: T.accent, fontFamily: 'var(--mono)', fontSize: 9,
            letterSpacing: '0.12em', padding: '4px 8px', cursor: 'pointer',
            flexShrink: 0,
          }}
        >→ NOW</button>
      )}
      {!task.isHabit && onEditDescription && (
        <button
          onClick={() => setDescOpen(o => !o)}
          aria-label={hasDesc ? 'Show / edit note' : 'Add note'}
          style={{
            width: 26, height: 26, flexShrink: 0, padding: 0,
            border: 'none', background: 'transparent',
            color: hasDesc ? T.accent : T.fg3,
            fontFamily: 'var(--mono)', fontSize: 11, lineHeight: 1, cursor: 'pointer',
          }}
        >{descOpen ? '▾' : (hasDesc ? '▸●' : '▸')}</button>
      )}
      {!task.isHabit && onDelete && (
        <button
          onClick={() => onDelete(task.id)}
          aria-label="Delete task"
          style={{
            width: 26, height: 26, flexShrink: 0, padding: 0,
            border: 'none', background: 'transparent', color: T.fg3,
            fontSize: 16, lineHeight: 1, cursor: 'pointer',
          }}
        >×</button>
      )}
    </div>
    {descOpen && !task.isHabit && (
      <div style={{ padding: '0 20px 12px', background: T.panel2 }}>
        <textarea
          value={desc}
          onChange={(e) => setDesc(e.target.value)}
          onBlur={commitDesc}
          placeholder="Optional note."
          rows={3}
          style={{
            width: '100%', resize: 'vertical', minHeight: 60,
            border: `1px solid ${T.line}`, outline: 'none', background: T.panel,
            fontFamily: 'var(--sans)', fontSize: 13, color: T.fg,
            padding: 10,
          }}
        />
      </div>
    )}
    </div>
  );
}

Object.assign(window, { HabitsPanel, MobileView, MobileTaskRow });
