// First-Month Wizard — dashboard, drawer, export
// Requires SetupWizard, tasksForProfile, fmwHelpers from fmw-setup.jsx

const { todayISO, daysBetween, addDays, fmtDate } = window.fmwHelpers;

// ═══════════════════════════════════════════════════════════════════════════
// EXPORT HELPERS
// ═══════════════════════════════════════════════════════════════════════════

function exportMarkdown(tasks, profile) {
  let md = `# My First Month in ${profile.country === 'us' ? 'the US' : 'Canada'}\n\n`;
  md += `_Arrival: ${fmtDate(profile.arrivalDate)} · Generated by NRI Outpost_\n\n`;
  [1,2,3,4].forEach(w => {
    const wt = tasks.filter(t => t.week === w);
    if (!wt.length) return;
    md += `## Week ${w}\n\n`;
    wt.forEach(t => {
      const check = t.done ? 'x' : ' ';
      md += `- [${check}] **${t.title}** — Day ${t.day} (${fmtDate(t.dueDate)})\n`;
      md += `  ${t.short}\n`;
      (t.subItems || []).forEach(s => {
        md += `  - [ ] ${s}\n`;
      });
      md += `\n`;
    });
  });
  return md;
}

function exportCSV(tasks, profile) {
  const esc = (s) => `"${String(s || '').replace(/"/g, '""')}"`;
  let csv = 'TYPE,CONTENT,PRIORITY,INDENT,AUTHOR,RESPONSIBLE UID,DATE,DATE_LANG,TIMEZONE,DURATION,DURATION UNIT,DEADLINE,DEADLINE_LANG\n';
  // Todoist's import format. PRIORITY 4=highest. INDENT 1=top, 2=subtask.
  tasks.forEach(t => {
    const pri = t.priority === 'high' ? 4 : t.priority === 'medium' ? 3 : 2;
    csv += `task,${esc(t.title)},${pri},1,,,${esc(fmtDate(t.dueDate))},en,,,,\n`;
    csv += `note,${esc(t.short)},,1,,,,,,,,\n`;
    (t.subItems || []).forEach(s => {
      csv += `task,${esc(s)},${pri},2,,,${esc(fmtDate(t.dueDate))},en,,,,\n`;
    });
  });
  return csv;
}

function exportPlain(tasks, profile) {
  let txt = `My First Month in ${profile.country === 'us' ? 'the US' : 'Canada'}\n`;
  txt += `Arrival: ${fmtDate(profile.arrivalDate)}\n\n`;
  [1,2,3,4].forEach(w => {
    const wt = tasks.filter(t => t.week === w);
    if (!wt.length) return;
    txt += `\n=== WEEK ${w} ===\n\n`;
    wt.forEach(t => {
      txt += `[${t.done ? 'X' : ' '}] ${t.title} (Day ${t.day}, ${fmtDate(t.dueDate)})\n`;
      txt += `    ${t.short}\n`;
      (t.subItems || []).forEach(s => txt += `    - ${s}\n`);
      txt += `\n`;
    });
  });
  return txt;
}

function exportICS(tasks, profile) {
  const pad = (n) => String(n).padStart(2, '0');
  const fmtICSDate = (iso) => iso.replace(/-/g, '');
  const stamp = () => {
    const d = new Date();
    return `${d.getUTCFullYear()}${pad(d.getUTCMonth()+1)}${pad(d.getUTCDate())}T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`;
  };
  let ics = 'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//NRI Outpost//First Month//EN\r\nCALSCALE:GREGORIAN\r\nMETHOD:PUBLISH\r\n';
  tasks.forEach(t => {
    const date = fmtICSDate(t.dueDate);
    const summary = `📋 ${t.title}`;
    const desc = `${t.short}\\n\\n${(t.subItems || []).map(s => `• ${s}`).join('\\n')}\\n\\nFrom NRI Outpost First-Month Wizard.`;
    ics += 'BEGIN:VEVENT\r\n';
    ics += `UID:${t.id}-${date}@nri-outpost\r\n`;
    ics += `DTSTAMP:${stamp()}\r\n`;
    ics += `DTSTART;VALUE=DATE:${date}\r\n`;
    ics += `DTEND;VALUE=DATE:${date}\r\n`;
    ics += `SUMMARY:${summary}\r\n`;
    ics += `DESCRIPTION:${desc}\r\n`;
    ics += `CATEGORIES:${t.category}\r\n`;
    if (t.priority === 'high') ics += 'PRIORITY:1\r\n';
    ics += 'BEGIN:VALARM\r\nACTION:DISPLAY\r\nDESCRIPTION:Reminder\r\nTRIGGER:-P1D\r\nEND:VALARM\r\n';
    ics += 'END:VEVENT\r\n';
  });
  ics += 'END:VCALENDAR\r\n';
  return ics;
}

function download(filename, content, mime = 'text/plain') {
  const blob = new Blob([content], { type: mime + ';charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = filename;
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

async function copyToClipboard(text) {
  try { await navigator.clipboard.writeText(text); return true; }
  catch { return false; }
}

// ═══════════════════════════════════════════════════════════════════════════
// EXPORT MODAL
// ═══════════════════════════════════════════════════════════════════════════

function ExportModal({ tasks, profile, onClose }) {
  const [copied, setCopied] = useState('');
  const handleCopy = async (type, content) => {
    const ok = await copyToClipboard(content);
    if (ok) {
      setCopied(type);
      setTimeout(() => setCopied(''), 2000);
    }
  };

  const formats = [
    {
      id: 'md', name: 'Markdown', icon: '◐',
      apps: 'Notion · OneNote · Apple Notes · Obsidian · Bear · GitHub',
      desc: 'Renders as proper checkboxes in any markdown-aware app.',
      action: 'copy',
      build: () => exportMarkdown(tasks, profile),
    },
    {
      id: 'ics', name: 'Calendar (.ics)', icon: '☷',
      apps: 'Google Calendar · Apple Calendar · Outlook · Fantastical',
      desc: 'Each task becomes an all-day event with a reminder the day before.',
      action: 'download',
      filename: 'nri-first-month.ics',
      mime: 'text/calendar',
      build: () => exportICS(tasks, profile),
    },
    {
      id: 'csv', name: 'Todoist CSV', icon: '⊞',
      apps: 'Todoist · TickTick · Things (via TickTick)',
      desc: 'Drop directly into Todoist as a project template.',
      action: 'download',
      filename: 'nri-first-month-todoist.csv',
      mime: 'text/csv',
      build: () => exportCSV(tasks, profile),
    },
    {
      id: 'txt', name: 'Plain text', icon: '☰',
      apps: 'Anywhere · Microsoft To Do (paste line-by-line) · Google Tasks',
      desc: 'Universal fallback. Paste into any app that accepts text.',
      action: 'copy',
      build: () => exportPlain(tasks, profile),
    },
  ];

  return (
    <div className={'modal-bg open'} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 620 }}>
        <h2>Export your plan</h2>
        <p className="modal-sub">Send your personalized 30-day plan to any to-do app, calendar, or notes app you already use. Everything below includes <strong>all {tasks.length} tasks</strong> with due dates and sub-items.</p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {formats.map(f => (
            <div key={f.id} style={{
              background: 'var(--card)',
              border: '1px solid var(--rule)',
              borderRadius: 14,
              padding: 18,
            }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                    <span style={{ fontFamily: 'Instrument Serif, serif', fontSize: 20, color: 'var(--saffron)' }}>{f.icon}</span>
                    <strong style={{ fontSize: 15 }}>{f.name}</strong>
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 6 }}>{f.apps}</div>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>{f.desc}</div>
                </div>
                <button
                  className="btn btn-primary"
                  style={{ padding: '10px 18px', fontSize: 13, flexShrink: 0 }}
                  onClick={() => {
                    const content = f.build();
                    if (f.action === 'copy') handleCopy(f.id, content);
                    else download(f.filename, content, f.mime);
                  }}
                >
                  {f.action === 'copy'
                    ? (copied === f.id ? '✓ Copied' : 'Copy')
                    : 'Download'}
                </button>
              </div>
            </div>
          ))}
        </div>

        <div className="modal-actions">
          <button className="btn btn-ghost" onClick={onClose}>Done</button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// DRAWER
// ═══════════════════════════════════════════════════════════════════════════

function TaskDrawer({ task, profile, onClose, onToggle, onToggleSub, subState }) {
  if (!task) return null;
  const days = daysBetween(todayISO(), task.dueDate);
  const dueText = days === 0 ? 'Today' : days < 0 ? `${Math.abs(days)} days ago` : `In ${days} days · ${fmtDate(task.dueDate)}`;
  return (
    <>
      <div className={'drawer-bg ' + (task ? 'open' : '')} onClick={onClose} />
      <div className={'drawer ' + (task ? 'open' : '')}>
        <div className="drawer-head">
          <div className="drawer-head-meta">Day {task.day} · {task.category}</div>
          <button className="drawer-close" onClick={onClose}>×</button>
        </div>
        <div className="drawer-body">
          <h2 className="drawer-title">{task.title}</h2>
          <div className="drawer-tags">
            <span className={'task-tag ' + (task.priority === 'high' ? 'high' : '')}>{task.priority}</span>
            <span className="task-tag day">{dueText}</span>
            {task.countries && task.countries.length === 1 && (
              <span className="task-tag">{task.countries[0] === 'us' ? '🇺🇸 US only' : '🇨🇦 CA only'}</span>
            )}
          </div>
          <div className="drawer-detail" dangerouslySetInnerHTML={{ __html: task.detail || `<p>${task.short}</p>` }} />

          {task.subItems && task.subItems.length > 0 && (
            <div className="drawer-section">
              <div className="drawer-h">Steps</div>
              <div className="drawer-subitems">
                {task.subItems.map((s, i) => {
                  const key = `${task.id}-${i}`;
                  const done = subState[key];
                  return (
                    <div key={i} className={'subitem ' + (done ? 'done' : '')} onClick={() => onToggleSub(key)}>
                      <div className="subitem-check"></div>
                      <div className="subitem-text">{s}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {task.links && task.links.length > 0 && (
            <div className="drawer-section">
              <div className="drawer-h">Helpful links</div>
              <div className="drawer-links">
                {task.links.map((l, i) => (
                  <a key={i} className="drawer-link" href={l.url} target="_blank" rel="noopener">
                    <div className="drawer-link-text">
                      {l.label}
                      {l.desc && <small>{l.desc}</small>}
                    </div>
                    <div className="drawer-link-arrow">↗</div>
                  </a>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="drawer-actions">
          <button className="btn btn-ghost" onClick={onClose}>Close</button>
          <button className="btn btn-primary" onClick={() => onToggle(task.id)}>
            {task.done ? '↩ Mark not done' : '✓ Mark as done'}
          </button>
        </div>
      </div>
    </>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════

function Dashboard({ profile, onEditProfile, onReset }) {
  const allTasks = useMemo(() => tasksForProfile(profile), [profile]);
  const [done, setDone] = useState(() => loadState().done || {});
  const [subDone, setSubDone] = useState(() => loadState().subDone || {});
  const [activeWeek, setActiveWeek] = useState(() => {
    const day = daysBetween(profile.arrivalDate, todayISO()) + 1;
    if (day <= 7) return 1;
    if (day <= 14) return 2;
    if (day <= 21) return 3;
    return 4;
  });
  const [openTaskId, setOpenTaskId] = useState(null);
  const [showExport, setShowExport] = useState(false);

  useEffect(() => {
    const s = loadState();
    saveState({ ...s, done, subDone });
  }, [done, subDone]);

  const tasks = useMemo(() => allTasks.map(t => ({ ...t, done: !!done[t.id] })), [allTasks, done]);
  const toggleDone = (id) => setDone(d => ({ ...d, [id]: !d[id] }));
  const toggleSub = (k) => setSubDone(s => ({ ...s, [k]: !s[k] }));

  const currentDay = daysBetween(profile.arrivalDate, todayISO()) + 1;
  const isFuture = currentDay < 1;
  const isDone = currentDay > 30;

  // Today's focus: 3 highest-priority not-done tasks closest to today
  const focusTasks = useMemo(() => {
    return [...tasks]
      .filter(t => !t.done)
      .sort((a, b) => {
        const pri = { high: 0, medium: 1, low: 2 };
        if (pri[a.priority] !== pri[b.priority]) return pri[a.priority] - pri[b.priority];
        return Math.abs(daysBetween(todayISO(), a.dueDate)) - Math.abs(daysBetween(todayISO(), b.dueDate));
      })
      .slice(0, 3);
  }, [tasks]);

  const weekTasks = tasks.filter(t => t.week === activeWeek);
  const weekProgress = (w) => {
    const wt = tasks.filter(t => t.week === w);
    const dn = wt.filter(t => t.done).length;
    return { done: dn, total: wt.length };
  };

  // Group week tasks by category
  const grouped = useMemo(() => {
    const g = {};
    weekTasks.forEach(t => { (g[t.category] = g[t.category] || []).push(t); });
    return g;
  }, [weekTasks]);

  // Timeline strip data — 30 days
  const stripDays = Array.from({ length: 30 }, (_, i) => {
    const date = addDays(profile.arrivalDate, i);
    const dayTasks = tasks.filter(t => t.day === i + 1);
    const dayDone = dayTasks.filter(t => t.done).length;
    const isPast = daysBetween(todayISO(), date) < 0;
    const isToday = date === todayISO();
    return { day: i + 1, date, tasks: dayTasks, done: dayDone, isPast, isToday };
  });

  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return 'Good morning';
    if (h < 18) return 'Good afternoon';
    return 'Good evening';
  })();

  const totalDone = tasks.filter(t => t.done).length;
  const totalTasks = tasks.length;
  const allDone = totalDone === totalTasks && totalTasks > 0;

  const openTask = tasks.find(t => t.id === openTaskId);

  return (
    <div className="dash">
      {/* Hero */}
      <div className="dash-hero">
        <div>
          <div className="greeting-eyebrow">
            <span className="greeting-dot"></span>
            Your personal NRI Outpost plan
          </div>
          <h1 className="greeting">
            {greeting}, <em>{profile.name}</em>.
          </h1>
          <p className="greeting-sub">
            {isFuture
              ? `You land in ${Math.abs(currentDay - 1)} days. Here's everything to do before takeoff and your first month in ${profile.city}.`
              : isDone
              ? `You've crossed day 30 in ${profile.city}. Nice work — keep going through anything left below.`
              : `Day ${currentDay} of 30 in ${profile.city}. Below are your tasks for this week, plus the few you still owe yourself.`}
          </p>
        </div>
        <div className="day-counter">
          <div>
            <div className="dc-label">{isFuture ? 'Days until arrival' : isDone ? 'Days since arrival' : 'Day'}</div>
            <div className="dc-number">
              {isFuture ? Math.abs(currentDay - 1) : isDone ? currentDay - 1 : currentDay}
              {!isFuture && !isDone && <small> / 30</small>}
            </div>
          </div>
          <div className="dc-arrival">
            Arrival · <strong>{fmtDate(profile.arrivalDate)}</strong> · {profile.country === 'us' ? '🇺🇸' : '🇨🇦'} {profile.city}
          </div>
        </div>
      </div>

      {/* Today / Up next */}
      <div className="today">
        <div className="section-h">
          <h2 className="serif">{isFuture ? 'Before you fly' : 'Today and up next'}</h2>
          <span className="section-h-meta">{totalDone}/{totalTasks} done · {Math.round(totalDone/Math.max(1,totalTasks)*100)}%</span>
        </div>
        {focusTasks.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', background: 'var(--card)', border: '1px solid var(--rule)', borderRadius: 18 }}>
            <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 42, lineHeight: 1.0, marginBottom: 12 }}>
              All caught up. <em style={{ fontStyle: 'italic', color: 'var(--saffron)' }}>Beautiful.</em>
            </div>
            <p style={{ color: 'var(--ink-2)' }}>You've ticked off every task. Treat yourself to a samosa.</p>
          </div>
        ) : (
          <div className="today-grid">
            {focusTasks.map(t => {
              const days = daysBetween(todayISO(), t.dueDate);
              const pill = days < 0 ? 'urgent' : days <= 1 ? 'due' : 'flexible';
              const pillText = days < 0 ? `${Math.abs(days)}d late` : days === 0 ? 'Today' : days === 1 ? 'Tomorrow' : `In ${days}d`;
              return (
                <div key={t.id} className={'today-card priority-' + t.priority} onClick={() => setOpenTaskId(t.id)}>
                  <div className="tc-top">
                    <span className="tc-cat">{t.category}</span>
                    <span className={'tc-pill ' + pill}>{pillText}</span>
                  </div>
                  <h3 className="tc-title">{t.title}</h3>
                  <p style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.45 }}>{t.short}</p>
                  <div className="tc-meta">
                    <span className="tc-time">Day {t.day} · {fmtDate(t.dueDate)}</span>
                    <span className="tc-action">Open →</span>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Weeks */}
      <div className="weeks">
        <div className="section-h">
          <h2 className="serif">The <em>full plan</em>, week by week</h2>
          <button className="btn btn-ghost" style={{ padding: '10px 18px', fontSize: 13 }} onClick={() => setShowExport(true)}>
            ↓ Export to to-do app
          </button>
        </div>

        <div className="week-tabs">
          {[1,2,3,4].map(w => {
            const p = weekProgress(w);
            return (
              <button key={w} className={'wt ' + (activeWeek === w ? 'active' : '')} onClick={() => setActiveWeek(w)}>
                <div className="wt-num">WEEK {w}</div>
                <div className="wt-title">
                  {w === 1 ? 'Bearings' : w === 2 ? 'Identity & admin' : w === 3 ? 'Credit & comfort' : 'Settle in'}
                </div>
                <div className="wt-progress">{p.done} / {p.total} done</div>
              </button>
            );
          })}
        </div>

        {Object.entries(grouped).map(([cat, items]) => (
          <div key={cat} className="task-section">
            <h3>{cat} · {items.length} task{items.length > 1 ? 's' : ''}</h3>
            <div className="task-list">
              {items.map(t => (
                <div key={t.id} className={'task ' + (t.done ? 'done' : '')} onClick={() => setOpenTaskId(t.id)}>
                  <div className="task-check" onClick={(e) => { e.stopPropagation(); toggleDone(t.id); }}></div>
                  <div className="task-text">
                    {t.title}
                    <small>{t.short}</small>
                  </div>
                  <div className="task-tags">
                    {t.priority === 'high' && <span className="task-tag high">priority</span>}
                    <span className="task-tag day">D{t.day} · {fmtDate(t.dueDate)}</span>
                  </div>
                  <div className="task-chev">›</div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Timeline strip */}
      <div className="timeline-strip">
        <div className="ts-head">
          <h3 className="serif">30-day overview</h3>
          <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>
            Hover a day for details
          </span>
        </div>
        <div className="ts-grid">
          {stripDays.map(d => (
            <div
              key={d.day}
              className={[
                'ts-day',
                d.tasks.length > 0 && 'has-tasks',
                d.tasks.length > 0 && d.done === d.tasks.length && 'has-done',
                d.isPast && 'past',
                d.isToday && 'today',
              ].filter(Boolean).join(' ')}
              title={`Day ${d.day} · ${fmtDate(d.date)} · ${d.tasks.length} task${d.tasks.length !== 1 ? 's' : ''}${d.tasks.length ? ` (${d.done} done)` : ''}`}
            ></div>
          ))}
        </div>
        <div className="ts-labels">
          <span>Day 1 · {fmtDate(profile.arrivalDate)}</span>
          <span>Day 30 · {fmtDate(addDays(profile.arrivalDate, 29))}</span>
        </div>
        <div className="ts-legend">
          <div className="ts-legend-item"><span className="ts-legend-swatch" style={{ background: 'var(--saffron-soft)' }}></span>Has tasks</div>
          <div className="ts-legend-item"><span className="ts-legend-swatch" style={{ background: 'var(--saffron)' }}></span>Complete</div>
          <div className="ts-legend-item"><span className="ts-legend-swatch" style={{ background: 'var(--ink)' }}></span>Today</div>
          <div className="ts-legend-item"><span className="ts-legend-swatch" style={{ background: 'var(--paper-2)' }}></span>Empty day</div>
        </div>
      </div>

      <TaskDrawer
        task={openTask}
        profile={profile}
        onClose={() => setOpenTaskId(null)}
        onToggle={(id) => { toggleDone(id); setOpenTaskId(null); }}
        onToggleSub={toggleSub}
        subState={subDone}
      />

      {showExport && <ExportModal tasks={tasks} profile={profile} onClose={() => setShowExport(false)} />}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// APP SHELL
// ═══════════════════════════════════════════════════════════════════════════

function App() {
  const [state, setState] = useState(loadState);
  const [editing, setEditing] = useState(false);

  const setProfile = (profile) => {
    const next = { ...state, profile };
    setState(next);
    saveState(next);
    setEditing(false);
  };

  const reset = () => {
    if (confirm('Reset your plan? This deletes all progress and your profile.')) {
      localStorage.removeItem(STORAGE_KEY);
      setState({});
    }
  };

  if (!state.profile || editing) {
    return (
      <>
        <TopBar profile={state.profile} onEdit={() => setEditing(true)} onReset={reset} hideProfile={!state.profile} />
        <SetupWizard initial={editing ? state.profile : null} onComplete={setProfile} />
      </>
    );
  }

  return (
    <>
      <TopBar profile={state.profile} onEdit={() => setEditing(true)} onReset={reset} />
      <Dashboard profile={state.profile} onEditProfile={() => setEditing(true)} onReset={reset} />
    </>
  );
}

function TopBar({ profile, onEdit, onReset, hideProfile }) {
  return (
    <div className="topbar">
      <div className="topbar-inner">
        <a href="/" className="brand" aria-label="NRI Outpost — Home" style={{ textDecoration: 'none', color: 'inherit' }}>
          <div className="brand-mark"></div>
          <span>NRI<em>Outpost</em></span>
          <div className="brand-sep"></div>
          <span className="brand-feature">First-Month <strong>Wizard</strong></span>
        </a>
        <div className="topbar-right">
          <a href="/" className="tb-link">← Back to main</a>
          {!hideProfile && profile && (
            <button className="profile-chip" onClick={onEdit}>
              <span className="avatar">{(profile.name || '?').charAt(0).toUpperCase()}</span>
              <span>
                {profile.name}
                <span className="profile-chip-meta" style={{ display: 'block', marginTop: -2 }}>
                  {profile.country === 'us' ? '🇺🇸' : '🇨🇦'} {profile.city} · {profile.role}
                </span>
              </span>
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
