// Komonichi — Today page: calendar strip, goals hierarchy, today's tasks, focus timer
const { useKomonichi, actions, sel, fmtMin, todayKey } = window.KomonichiState;

const JP_QUOTES = [
  { jp: '一期一会', romaji: 'ichigo ichie', en: 'One time, one meeting. This moment will not come again.' },
  { jp: '七転び八起き', romaji: 'nana korobi ya oki', en: 'Fall seven times, rise eight.' },
  { jp: '初心忘るべからず', romaji: 'shoshin wasuru bekarazu', en: 'Do not forget the beginner’s mind.' },
  { jp: '有難う', romaji: 'arigatou', en: '“To be” “difficult” — thank you means: your existence here is rare.' },
  { jp: '水に流す', romaji: 'mizu ni nagasu', en: 'Let it flow with the water. What is past, let pass.' },
  { jp: '昔は昔今は今', romaji: 'mukashi wa mukashi ima wa ima', en: 'The past was the past. Now is now.' },
  { jp: '続けることは力なり', romaji: 'tsuzukeru koto wa chikara nari', en: 'To continue is itself a kind of strength.' },
  { jp: '心ここにあらざれば', romaji: 'kokoro koko ni arazareba', en: 'If the heart is not here, the eye does not see.' },
  { jp: '余白', romaji: 'yohaku', en: 'The blank space. What is not painted is also the painting.' },
  { jp: '静かなる水は深し', romaji: 'shizuka naru mizu wa fukashi', en: 'Still water runs deep.' },
  { jp: '今日の一針', romaji: 'kyou no ippari', en: 'Today’s single stitch — better than tomorrow’s thousand.' },
  { jp: '細流も海に至る', romaji: 'sairyuu mo umi ni itaru', en: 'Even the thinnest stream arrives at the sea.' },
];

function QuoteOfDay() {
  // pick by day-of-year so it changes each day; rotate hourly with subtle fade
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 60 * 1000);
    return () => clearInterval(id);
  }, []);
  const dayIdx = Math.floor((now - new Date(now.getFullYear(), 0, 0)) / 86400000);
  const q = JP_QUOTES[(dayIdx + now.getHours() % 3) % JP_QUOTES.length];
  return (
    <div key={q.jp} className="fade-in" style={{
      display: 'grid', gridTemplateColumns: 'auto 1px 1fr', gap: 22, alignItems: 'center',
      margin: '0 0 24px', padding: '4px 2px 18px',
    }}>
      <div style={{ textAlign: 'left' }}>
        <div className="display" style={{ fontSize: 36, lineHeight: 1.1, color: 'var(--ink)', letterSpacing: '0.02em' }}>{q.jp}</div>
        <div className="label" style={{ marginTop: 6, color: 'var(--persimmon)' }}>{q.romaji}</div>
      </div>
      <div style={{ height: 56, background: 'var(--paper-line)' }}></div>
      <div className="haiku" style={{ fontSize: 16 }}>
        <span className="line">“{q.en}”</span>
      </div>
    </div>
  );
}

function DailyNotes() {
  const [state] = useKomonichi();
  const k = todayKey();
  const stored = (state.notes && state.notes[k]) || '';
  const [text, setText] = React.useState(stored);
  // Pull today's note from the server on first mount (bootstrap doesn't include it).
  React.useEffect(() => {
    if (!(state.notes && k in state.notes)) {
      actions.loadNoteForDate(k).catch(() => {});
    }
  }, [k]);
  // Re-sync the textarea when the store updates (e.g. after a server load
  // or an edit in the Journal tab).
  React.useEffect(() => { setText(stored); }, [stored, k]);
  const [savedAt, setSavedAt] = React.useState(null);
  const tRef = React.useRef(null);

  const onChange = (v) => {
    setText(v);
    if (tRef.current) clearTimeout(tRef.current);
    tRef.current = setTimeout(() => {
      actions.setDailyNote(k, v);
      setSavedAt(new Date());
    }, 500);
  };

  return (
    <div className="card">
      <div className="cap">
        <div>
          <div className="label">a page kept open</div>
          <h3 className="title">today's <span className="em">notes</span></h3>
        </div>
        <span className="chip" style={{ opacity: savedAt ? 0.9 : 0.4 }}>
          {savedAt ? `saved · ${savedAt.toLocaleTimeString('en', { hour: 'numeric', minute: '2-digit' }).toLowerCase()}` : 'auto-save'}
        </span>
      </div>
      <textarea className="f"
        value={text}
        onChange={(e) => onChange(e.target.value)}
        placeholder="what arrived today — a thought, a person, an unfinished question…"
        style={{
          minHeight: 140, fontFamily: 'var(--serif)', fontSize: 17, lineHeight: 1.6,
          color: 'var(--ink)', background: 'transparent',
          borderBottom: 0,
          backgroundImage: 'repeating-linear-gradient(transparent, transparent 27px, var(--paper-line) 27px, var(--paper-line) 28px)',
          padding: '2px 0',
        }} />
      <div className="label" style={{ marginTop: 10, fontStyle: 'italic', opacity: 0.7 }}>
        kept on the page, not the wire. Each day begins a fresh sheet.
      </div>
    </div>
  );
}

function CalendarStrip() {
  const today = new Date();
  const days = [];
  for (let i = -3; i <= 3; i++) {
    const d = new Date(today); d.setDate(today.getDate() + i);
    days.push(d);
  }
  return (
    <div style={{ display: 'flex', gap: 0, borderTop: '1px solid var(--paper-line)', borderBottom: '1px solid var(--paper-line)' }}>
      {days.map((d, i) => {
        const isToday = d.toDateString() === today.toDateString();
        return (
          <div key={i} style={{
            flex: 1, textAlign: 'center', padding: '14px 8px',
            borderRight: i < days.length - 1 ? '1px dashed var(--paper-line)' : 0,
            background: isToday ? 'rgba(179,90,58,0.06)' : 'transparent',
          }}>
            <div className="label" style={{ color: isToday ? 'var(--persimmon)' : 'var(--ink-faint)' }}>
              {d.toLocaleString('en', { weekday: 'short' })}
            </div>
            <div className="num" style={{ fontSize: 22, marginTop: 4, color: isToday ? 'var(--ink)' : 'var(--ink-soft)', fontWeight: isToday ? 500 : 300 }}>
              {d.getDate()}
            </div>
            <div className="label" style={{ marginTop: 2, fontSize: 8 }}>
              {d.toLocaleString('en', { month: 'short' })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function GoalRow({ obj, scale, tone }) {
  return (
    <div style={{ padding: '11px 0', borderBottom: '1px dashed var(--paper-line)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
        <div className="display" style={{ fontSize: 17, color: 'var(--ink)' }}>{obj.text}</div>
        <span className={`chip ${tone}`}>{scale}</span>
      </div>
      <div className="label" style={{ marginTop: 4, opacity: 0.75 }}>{obj.period}</div>
    </div>
  );
}

function TodayPage() {
  const [state] = useKomonichi();
  const [timerTaskId, setTimerTaskId] = React.useState(null);
  const [showTimer, setShowTimer] = React.useState(false);
  const [reschedBusy, setReschedBusy] = React.useState(false);

  const today = todayKey();
  // Today list = only tasks explicitly scheduled for today.
  const todaysTasks = state.tasks
    .filter(t => t.status === 'open' && t.dueDate === today)
    .slice(0, 8);
  const overdueTasks = state.tasks
    .filter(t => t.status === 'open' && t.dueDate && t.dueDate < today);
  const doneToday = state.tasks.filter(t => t.status === 'done' && t.completedAt && new Date(t.completedAt).toDateString() === new Date().toDateString());

  async function rescheduleAll() {
    if (reschedBusy) return;
    setReschedBusy(true);
    try { await actions.rescheduleOverdueToToday(); }
    finally { setReschedBusy(false); }
  }
  const todayMin = sel.todayMinutes(state);
  const target = state.settings.dailyFocusTargetMin;
  const pct = sel.todayTargetPct(state);
  const todayBadges = state.badges.filter(b => b.date === window.KomonichiState.todayKey());

  const startFor = (id) => { setTimerTaskId(id); setShowTimer(true); };

  return (
    <div className="fade-in">
      {/* header line */}
      <div className="page-head" style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'end', marginBottom: 22, gap: 18 }}>
        <div>
          <div className="label">{new Date().toLocaleString('en', { weekday: 'long' })}</div>
          <h2 className="display page-title" style={{ fontSize: 48, lineHeight: 1, margin: '8px 0 0' }}>
            today, <span style={{ color: 'var(--persimmon)' }}>{new Date().toLocaleString('en', { month: 'long' }).toLowerCase()} {new Date().getDate()}</span>
          </h2>
        </div>
        <div className="today-meter" style={{ textAlign: 'right' }}>
          <div className="label">attended</div>
          <div className="num" style={{ fontSize: 30, fontWeight: 300 }}>{fmtMin(todayMin)}<span style={{ color: 'var(--ink-ghost)', fontSize: 14 }}> / {fmtMin(target)}</span></div>
          <div className="today-meter-bar" style={{ width: 180, height: 2, background: 'var(--paper-line)', marginTop: 6, marginLeft: 'auto' }}>
            <div style={{ width: `${pct}%`, height: '100%', background: 'var(--persimmon)', transition: 'width 0.8s ease' }}></div>
          </div>
        </div>
      </div>

      <QuoteOfDay />
      <div style={{ marginBottom: 28 }}><CalendarStrip /></div>

      <div className="grid g-12">
        {/* left column: tasks + timer */}
        <div className="c-7" style={{ display: 'grid', gap: 22 }}>
          {overdueTasks.length > 0 && (
            <div className="card" style={{ borderColor: 'rgba(196,108,74,0.4)' }}>
              <div className="cap">
                <div>
                  <div className="label" style={{ color: 'var(--persimmon)' }}>missed the day</div>
                  <h3 className="title"><span className="em">overdue</span></h3>
                </div>
                <button className="btn warm tiny"
                  onClick={rescheduleAll}
                  disabled={reschedBusy}
                  title={`reschedule ${overdueTasks.length} task${overdueTasks.length === 1 ? '' : 's'} to today`}>
                  {reschedBusy ? 'rescheduling…' : 'reschedule to today'}
                </button>
              </div>
              {overdueTasks.map(t => (
                <div key={t.id} style={{
                  display: 'grid', gridTemplateColumns: '1fr auto',
                  gap: 12, alignItems: 'baseline', padding: '10px 0',
                  borderBottom: '1px dashed var(--paper-line)',
                }}>
                  <div>
                    <div style={{ fontSize: 14 }}>{t.title}</div>
                    <div className="label" style={{ marginTop: 3, color: 'var(--persimmon)' }}>
                      was due {new Date(t.dueDate + 'T00:00').toLocaleString('en', { month: 'short', day: 'numeric' })}
                    </div>
                  </div>
                  <span className="chip warm">overdue</span>
                </div>
              ))}
            </div>
          )}
          <div className="card">
            <div className="cap">
              <div>
                <div className="label">to attend to</div>
                <h3 className="title">today's <span className="em">three lines</span></h3>
              </div>
              <span className="chip">{todaysTasks.length} open</span>
            </div>
            {todaysTasks.length === 0 && (
              <div className="haiku" style={{ padding: '20px 0' }}>
                <span className="line">No tasks remain.</span>
                <span className="line">The bowl is empty — perhaps</span>
                <span className="line">that is the practice.</span>
              </div>
            )}
            <div>
              {todaysTasks.map(t => {
                const obj = t.objectiveId ? sel.objectiveById(state, t.objectiveId) : null;
                return (
                  <div key={t.id} style={{
                    display: 'grid', gridTemplateColumns: '20px 1fr auto auto',
                    gap: 14, alignItems: 'center', padding: '13px 0',
                    borderBottom: '1px dashed var(--paper-line)',
                  }}>
                    <button onClick={() => actions.toggleTaskDone(t.id)} aria-label="toggle"
                      style={{
                        width: 18, height: 18, borderRadius: '50%',
                        border: '1px solid var(--ink-soft)', background: 'transparent',
                        padding: 0, cursor: 'pointer',
                      }} />
                    <div>
                      <div style={{ fontSize: 15 }}>{t.title}</div>
                      {obj ? <div className="label" style={{ marginTop: 3, opacity: 0.8 }}>↳ {obj.text}</div> : null}
                    </div>
                    <span className="chip">{t.estimateMin}m</span>
                    <button className="btn tiny warm" onClick={() => startFor(t.id)}>focus</button>
                  </div>
                );
              })}
            </div>
            {doneToday.length > 0 && (
              <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--paper-line)' }}>
                <div className="label" style={{ marginBottom: 8 }}>kept today</div>
                {doneToday.map(t => (
                  <div key={t.id} style={{ fontSize: 13, color: 'var(--ink-faint)', textDecoration: 'line-through', textDecorationColor: 'var(--ink-ghost)', padding: '3px 0' }}>
                    {t.title}
                  </div>
                ))}
              </div>
            )}
          </div>

          {showTimer ? (
            <FocusTimer defaultTaskId={timerTaskId} onClose={() => setShowTimer(false)} />
          ) : (
            <div className="card" style={{ textAlign: 'center', padding: '34px 28px' }}>
              <div className="enso breathe" style={{ margin: '0 auto 18px' }}></div>
              <div className="label">begin a session</div>
              <h3 className="display" style={{ fontSize: 28, margin: '6px 0 16px' }}>sit with one thing</h3>
              <button className="btn warm" onClick={() => setShowTimer(true)}>open the timer</button>
            </div>
          )}

          <DailyNotes />
        </div>

        {/* right column: goals hierarchy + badges */}
        <div className="c-5" style={{ display: 'grid', gap: 22 }}>
          <div className="card">
            <div className="cap">
              <div>
                <div className="label">unedited</div>
                <h3 className="title"><span className="em">objectives</span> in view</h3>
              </div>
            </div>
            {state.objectives.yearly.map(o => <GoalRow key={o.id} obj={o} scale="year" tone="warm" />)}
            {state.objectives.quarterly.map(o => <GoalRow key={o.id} obj={o} scale="quarter" tone="indigo" />)}
            {state.objectives.monthly.map(o => <GoalRow key={o.id} obj={o} scale="month" tone="moss" />)}
            {state.objectives.weekly.map(o => <GoalRow key={o.id} obj={o} scale="week" tone="gold" />)}
            <div style={{ marginTop: 14, fontSize: 11, color: 'var(--ink-faint)', fontStyle: 'italic' }}>
              Once an objective is set down, it remains. Only the work changes.
            </div>
          </div>

          <div className="card">
            <div className="cap">
              <div>
                <div className="label">earned, lightly</div>
                <h3 className="title">today's <span className="em">marks</span></h3>
              </div>
              <span className="chip warm">{todayBadges.length}</span>
            </div>
            {todayBadges.length === 0 ? (
              <div className="haiku">
                <span className="line">The day is open.</span>
                <span className="line">No marks yet — the brush rests,</span>
                <span className="line">paper still untouched.</span>
              </div>
            ) : (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14 }}>
                {todayBadges.map(b => (
                  <div key={b.id} style={{ textAlign: 'center', width: 110 }}>
                    <div style={{
                      width: 64, height: 64, borderRadius: '50%',
                      border: '1px solid var(--persimmon)', margin: '0 auto 8px',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      background: 'radial-gradient(circle at 32% 30%, rgba(179,90,58,0.18), transparent 70%)',
                      boxShadow: 'inset 3px -4px 0 -2px var(--paper), inset -6px 5px 0 -3px var(--paper-deep)',
                    }}>
                      <span className="display" style={{ color: 'var(--persimmon)', fontSize: 26 }}>○</span>
                    </div>
                    <div className="display" style={{ fontSize: 13, lineHeight: 1.3, color: 'var(--ink-soft)' }}>{b.label}</div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.TodayPage = TodayPage;
