// Dashboard with three layout variants: timeline, checklist, grid.

const TaskIcon = ({ name, color }) => {
  const C = I[name] || I.doc;
  return (
    <div className="task-icon" style={{ background: color }}>
      <C size={16} />
    </div>
  );
};

// completion logic shared
const isDone = (taskId, progress) => COMPLETED_BY_PROGRESS[progress]?.has(taskId);

// ──────────────── Hero header (greeting + progress) ────────────────
function DashboardHero({ persona, progress, onJump }) {
  const tasks = TASKS(persona);
  const total = tasks.length;
  const done  = tasks.filter(t => isDone(t.id, progress)).length;
  const pct   = Math.round(done / total * 100);
  const day = progress === "day1" ? "Day 1" : progress === "week1" ? "Week 1" : "All set";

  return (
    <div className="hero card fade-up">
      <div className="hero-bg" aria-hidden="true">
        <svg viewBox="0 0 800 200" preserveAspectRatio="none">
          <defs>
            <linearGradient id="heroGrad" x1="0" x2="1">
              <stop offset="0" stopColor="var(--accent)" stopOpacity=".22"/>
              <stop offset="1" stopColor="var(--accent)" stopOpacity="0"/>
            </linearGradient>
          </defs>
          <path d="M0 140 Q 140 80 280 110 T 580 90 T 800 60 V200 H0 Z" fill="url(#heroGrad)"/>
          <path d="M0 170 Q 200 130 400 150 T 800 130 V200 H0 Z" fill="url(#heroGrad)" opacity=".5"/>
        </svg>
      </div>
      <div className="hero-inner">
        <div className="hero-text">
          <span className="eyebrow">
            <span className="live-dot" style={{ marginRight: 6 }}></span>
            {day} · {PERSONAS[persona].startDate}
          </span>
          <h1 className="hero-title">
            {progress === "done"
              ? <>Welcome aboard, {NEW_HIRE.first}. <span className="hero-accent">You're all set.</span></>
              : <>Welcome to Convoso, <span className="hero-accent">{NEW_HIRE.first}</span>.</>}
          </h1>
          <p className="hero-sub">
            {progress === "done"
              ? "Onboarding complete — your team is ready when you are. Here's a quick look at what's coming this week."
              : `You have ${total - done} ${total - done === 1 ? "task" : "tasks"} left in your onboarding plan. Most people finish in about ${progress === "day1" ? "two more hours" : "twenty minutes"}.`}
          </p>
          <div className="hero-meta">
            <div className="hm">
              <Avatar name={PERSONAS[persona].manager} size="sm"/>
              <div>
                <div className="hm-l">Your manager</div>
                <div className="hm-v">{PERSONAS[persona].manager}</div>
              </div>
            </div>
            <div className="hm">
              <I.briefcase size={28} style={{ color: "var(--text-muted)" }}/>
              <div>
                <div className="hm-l">Role</div>
                <div className="hm-v">{PERSONAS[persona].role}</div>
              </div>
            </div>
            <div className="hm">
              <I.building size={28} style={{ color: "var(--text-muted)" }}/>
              <div>
                <div className="hm-l">Location</div>
                <div className="hm-v">{PERSONAS[persona].location}</div>
              </div>
            </div>
          </div>
        </div>
        <div className="hero-progress">
          <svg width="148" height="148" viewBox="0 0 148 148">
            <circle cx="74" cy="74" r="62" fill="none" stroke="var(--border)" strokeWidth="9"/>
            <circle cx="74" cy="74" r="62" fill="none" stroke="var(--accent)" strokeWidth="9"
              strokeLinecap="round"
              strokeDasharray={`${(pct / 100) * (Math.PI * 124)} 999`}
              transform="rotate(-90 74 74)"
              style={{ transition: "stroke-dasharray .8s ease" }}/>
          </svg>
          <div className="hero-progress-label">
            <div className="hp-pct">{pct}<span>%</span></div>
            <div className="hp-sub">{done} of {total} done</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ──────────────── Quick stats row ────────────────
function QuickStats({ persona, progress, onNav }) {
  const tasks = TASKS(persona);
  const docCount = DOCS.filter(d => d.status === "pending").length;
  const meetingCount = MEETINGS[0].items.length;
  const trainCount = TRAININGS.filter(t => t.required && t.progress < 100).length;

  const items = [
    { k: "meetings", icon: "calendar", label: "Meetings today", value: meetingCount, hint: "Next at 11:00 AM", color: "#2563eb" },
    { k: "documents", icon: "doc", label: "Documents to sign", value: docCount, hint: "2 due tomorrow", color: "#f97316" },
    { k: "training", icon: "book", label: "Trainings required", value: trainCount, hint: "12 hours total", color: "#a855f7" },
    { k: "insurance", icon: "shield", label: "Benefits enrollment", value: "30d", hint: "Window closes Jun 11", color: "#16a34a" },
  ];

  return (
    <div className="qs-grid">
      {items.map(it => {
        const C = I[it.icon];
        return (
          <button key={it.k} className="qs-card" onClick={() => onNav(it.k)}>
            <div className="qs-icon" style={{ background: it.color + "1f", color: it.color }}>
              <C size={18}/>
            </div>
            <div className="qs-body">
              <div className="qs-value t-display">{it.value}</div>
              <div className="qs-label">{it.label}</div>
              <div className="qs-hint">{it.hint}</div>
            </div>
            <I.arrow size={14} style={{ color: "var(--text-subtle)" }}/>
          </button>
        );
      })}
    </div>
  );
}

// ──────────────── TIMELINE layout ────────────────
function TimelineLayout({ persona, progress, onNav }) {
  const tasks = TASKS(persona);
  const phases = [
    { id: "day1",   label: "Day 1",   sub: "Mon · May 11",      tone: "accent" },
    { id: "week1",  label: "Week 1",  sub: "May 11 – May 15",   tone: "info" },
    { id: "month1", label: "Month 1", sub: "May 11 – Jun 11",   tone: "muted" },
  ];

  return (
    <div className="timeline">
      {phases.map((ph, i) => {
        const phaseTasks = tasks.filter(t => t.phase === ph.id);
        const phaseDone = phaseTasks.filter(t => isDone(t.id, progress)).length;
        const allDone = phaseDone === phaseTasks.length;
        return (
          <div key={ph.id} className="tl-phase">
            <div className="tl-stem">
              <div className={"tl-bullet " + (allDone ? "done" : phaseDone > 0 ? "active" : "")}>
                {allDone ? <I.check size={12}/> : <span>{i + 1}</span>}
              </div>
              {i < phases.length - 1 && <div className="tl-line"/>}
            </div>
            <div className="tl-content">
              <div className="tl-head">
                <div>
                  <div className="tl-title">{ph.label}</div>
                  <div className="tl-sub">{ph.sub}</div>
                </div>
                <div className="tl-progress">
                  <span className="tnum">{phaseDone}/{phaseTasks.length}</span>
                  <div className="bar" style={{ width: 80 }}>
                    <i style={{ width: `${(phaseDone / phaseTasks.length) * 100}%` }}/>
                  </div>
                </div>
              </div>
              <div className="tl-tasks">
                {phaseTasks.map(t => (
                  <TaskRow key={t.id} t={t} done={isDone(t.id, progress)} onNav={onNav}/>
                ))}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

const KIND_TONE = {
  meeting: { label: "Meeting", color: "#2563eb", icon: "calendar", nav: "meetings" },
  doc:     { label: "Document", color: "#f97316", icon: "doc", nav: "documents" },
  training:{ label: "Training", color: "#a855f7", icon: "book", nav: "training" },
  task:    { label: "Task", color: "#0891b2", icon: "check", nav: null },
  media:   { label: "Watch", color: "#ec4899", icon: "play", nav: null },
};

function TaskRow({ t, done, onNav }) {
  const tone = KIND_TONE[t.kind] || KIND_TONE.task;
  const TIcon = I[t.icon] || I[tone.icon];
  return (
    <div className={"task-row" + (done ? " is-done" : "")}>
      <div className={"tick" + (done ? " done" : "")}>
        <I.check size={12}/>
      </div>
      <div className="task-icon-wrap" style={{ background: tone.color + "1f", color: tone.color }}>
        <TIcon size={15}/>
      </div>
      <div className="task-main">
        <div className="task-title">{t.title}</div>
        <div className="task-meta">
          <span className="chip chip-dot" style={{ color: tone.color, background: tone.color + "14", borderColor: "transparent" }}>{tone.label}</span>
          {t.time && <span className="muted">{t.time}</span>}
          {t.duration && <span className="subtle">· {t.duration}</span>}
          {t.deadline && <span className="chip chip-warn">Due in {t.deadline}</span>}
          {t.required && <span className="chip">Required</span>}
          {t.count && <span className="subtle">· {t.count}</span>}
        </div>
      </div>
      {tone.nav ? (
        <button className="btn btn-soft btn-sm" onClick={() => onNav(tone.nav)}>
          {done ? "View" : "Open"} <I.arrow size={12}/>
        </button>
      ) : (
        <button className="btn btn-ghost btn-sm">{done ? "Replay" : "Start"}</button>
      )}
    </div>
  );
}

// ──────────────── CHECKLIST layout ────────────────
function ChecklistLayout({ persona, progress, onNav }) {
  const tasks = TASKS(persona);
  const groups = [
    { id: "required", label: "Required this week", tasks: tasks.filter(t => t.required && t.phase !== "month1") },
    { id: "month",    label: "First 30 days",       tasks: tasks.filter(t => t.phase === "month1") },
    { id: "optional", label: "Recommended",         tasks: tasks.filter(t => !t.required && t.phase !== "month1") },
  ];
  return (
    <div className="checklist">
      {groups.map(g => (
        <div key={g.id} className="card card-pad">
          <div className="cl-head">
            <h3 className="cl-title">{g.label}</h3>
            <span className="muted tnum">
              {g.tasks.filter(t => isDone(t.id, progress)).length} / {g.tasks.length} complete
            </span>
          </div>
          <div className="cl-list">
            {g.tasks.map(t => <TaskRow key={t.id} t={t} done={isDone(t.id, progress)} onNav={onNav}/>)}
          </div>
        </div>
      ))}
    </div>
  );
}

// ──────────────── GRID layout ────────────────
function GridLayout({ persona, progress, onNav }) {
  const tasks = TASKS(persona);
  const cats = [
    { id: "meeting", label: "Meetings & 1:1s", icon: "calendar" },
    { id: "doc", label: "Paperwork & Forms", icon: "doc" },
    { id: "training", label: "Training", icon: "book" },
    { id: "task", label: "Setup tasks", icon: "laptop" },
    { id: "media", label: "Watch", icon: "play" },
  ];
  return (
    <div className="grid-layout">
      {cats.map(c => {
        const cTasks = tasks.filter(t => t.kind === c.id);
        if (!cTasks.length) return null;
        const C = I[c.icon];
        const tone = KIND_TONE[c.id];
        const cDone = cTasks.filter(t => isDone(t.id, progress)).length;
        return (
          <div key={c.id} className="card card-pad gl-card">
            <div className="gl-head">
              <div className="gl-icon" style={{ background: tone.color + "1f", color: tone.color }}>
                <C size={18}/>
              </div>
              <div className="gl-text">
                <div className="gl-title">{c.label}</div>
                <div className="muted" style={{ fontSize: 12 }}>{cDone} / {cTasks.length} complete</div>
              </div>
            </div>
            <div className="gl-list">
              {cTasks.slice(0, 4).map(t => (
                <div key={t.id} className={"gl-item" + (isDone(t.id, progress) ? " is-done" : "")}>
                  <div className={"tick" + (isDone(t.id, progress) ? " done" : "")}>
                    <I.check size={11}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="gl-item-title">{t.title}</div>
                    <div className="gl-item-meta">{t.time || t.duration}</div>
                  </div>
                </div>
              ))}
              {cTasks.length > 4 && <div className="gl-more muted">+ {cTasks.length - 4} more</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ──────────────── Side panel: today's events ────────────────
function TodayPanel({ onNav }) {
  const today = MEETINGS[0];
  return (
    <div className="card today-card">
      <div className="today-head">
        <div>
          <div className="muted" style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".06em", textTransform: "uppercase" }}>Today · {today.day} {today.date}</div>
          <h3 style={{ margin: "4px 0 0", fontSize: 16, fontWeight: 700, letterSpacing: "-0.015em" }}>Your schedule</h3>
        </div>
        <button className="btn btn-soft btn-sm" onClick={() => onNav("meetings")}>
          Open calendar
        </button>
      </div>
      <div className="today-list">
        {today.items.map((m, i) => (
          <div key={i} className={"today-item" + (m.primary ? " is-primary" : "")}>
            <div className="ti-time">
              <div className="ti-h">{m.time}</div>
              <div className="ti-d">{m.end}</div>
            </div>
            <div className={"ti-bar " + (m.primary ? "primary" : "")}/>
            <div className="ti-body">
              <div className="ti-title">{m.title}</div>
              <div className="ti-meta">
                <span>{m.with}</span>
                <span className="dot">·</span>
                <span>{m.loc}</span>
                {m.loc === "Zoom" && <button className="ti-join">Join</button>}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ──────────────── Buddy / manager card ────────────────
function PeopleCard({ persona }) {
  const p = PERSONAS[persona];
  const buddy = persona === "eng" ? { name: "Sam Liu", role: "Senior Engineer · Voice Infra" }
              : persona === "design" ? { name: "Devon Cole", role: "Senior Product Designer" }
              : { name: "Maya Cruz", role: "AE · Mid-Market" };
  return (
    <div className="card card-pad">
      <div className="eyebrow" style={{ marginBottom: 10 }}>Your people</div>
      <div className="people-row">
        <Avatar name={p.manager} size="md"/>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600 }}>{p.manager}</div>
          <div className="muted" style={{ fontSize: 12 }}>{p.managerRole}</div>
        </div>
        <button className="icon-btn" title="Message"><I.mail size={15}/></button>
      </div>
      <div className="divider" style={{ margin: "12px 0" }}/>
      <div className="people-row">
        <Avatar name={buddy.name} size="md"/>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600 }}>{buddy.name}</div>
          <div className="muted" style={{ fontSize: 12 }}>{buddy.role} · Buddy</div>
        </div>
        <button className="icon-btn" title="Message"><I.mail size={15}/></button>
      </div>
      <div className="divider" style={{ margin: "12px 0" }}/>
      <div className="people-row">
        <Avatar name="Lila Park" size="md"/>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600 }}>Lila Park</div>
          <div className="muted" style={{ fontSize: 12 }}>People Operations</div>
        </div>
        <button className="icon-btn" title="Message"><I.mail size={15}/></button>
      </div>
    </div>
  );
}

// ──────────────── Resources ────────────────
function ResourcesCard() {
  const items = [
    { title: "Employee Handbook", meta: "PDF · 84 pages", icon: "book" },
    { title: "Convoso Brand & Voice", meta: "Notion", icon: "notion" },
    { title: "Engineering Wiki", meta: "Confluence", icon: "globe" },
    { title: "Office Map · DTLA HQ", meta: "PDF · 1 page", icon: "building" },
  ];
  return (
    <div className="card card-pad">
      <div className="eyebrow" style={{ marginBottom: 10 }}>Resources</div>
      <div className="col" style={{ gap: 4 }}>
        {items.map((r, i) => {
          const C = I[r.icon];
          return (
            <a key={i} className="resource" href="#">
              <div className="rs-icon"><C size={15}/></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="rs-title">{r.title}</div>
                <div className="muted" style={{ fontSize: 11.5 }}>{r.meta}</div>
              </div>
              <I.external size={13} style={{ color: "var(--text-subtle)" }}/>
            </a>
          );
        })}
      </div>
    </div>
  );
}

// ──────────────── Dashboard root ────────────────
function Dashboard({ persona, progress, layout, onNav }) {
  return (
    <div className="dashboard fade-up">
      <DashboardHero persona={persona} progress={progress} onNav={onNav}/>

      <QuickStats persona={persona} progress={progress} onNav={onNav}/>

      <div className="dash-split">
        <div className="dash-main">
          <div className="dash-section-head">
            <h2 className="dash-section-title t-display">Your onboarding plan</h2>
            <span className="muted" style={{ fontSize: 13 }}>
              {layout === "timeline" ? "By week" : layout === "checklist" ? "By priority" : "By category"}
            </span>
          </div>
          {layout === "timeline" && <TimelineLayout persona={persona} progress={progress} onNav={onNav}/>}
          {layout === "checklist" && <ChecklistLayout persona={persona} progress={progress} onNav={onNav}/>}
          {layout === "grid" && <GridLayout persona={persona} progress={progress} onNav={onNav}/>}
        </div>

        <div className="dash-side">
          <TodayPanel onNav={onNav}/>
          <PeopleCard persona={persona}/>
          <ResourcesCard/>
        </div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.TaskRow = TaskRow;
