// Dashboard — top-level product overview. Displayed without the settings sidebar.

const DashboardScreen = ({ data }) => {
  const cfg = window.APP_CONFIG;
  const firstName = data.user.name.split(" ")[0];
  const now = new Date();
  const hour = now.getHours();
  const greeting = hour < 5 ? "Up late" : hour < 12 ? "Good morning" : hour < 17 ? "Good afternoon" : "Good evening";

  const assessments = data.assessments || [];
  const tenants = data.tenants || [];
  const inFlight = assessments.filter(a => a.stage !== "Approved").length;
  const flagged  = assessments.filter(a => a.stage === "Flagged").length;
  const avgScore = assessments.length
    ? Math.round(assessments.reduce((s, a) => s + a.score, 0) / assessments.length)
    : 0;

  const stats = [
    { label: "Active assessments", value: inFlight, delta: "+3 this week", tone: "good", sub: `${assessments.length} total in portfolio` },
    { label: "Average score", value: avgScore, delta: "+2.4 pts", tone: "good", sub: "vs last 30 days" },
    { label: "Clients", value: tenants.length, delta: `${tenants.filter(t=>t.status==="Onboarding").length} onboarding`, tone: "neutral", sub: "" },
    { label: "Flagged for review", value: flagged, delta: flagged > 0 ? "needs attention" : "all clear", tone: flagged > 0 ? "warn" : "good", sub: "" },
  ];

  const days = data.assessmentsByDay || [];

  // Recent activity (mock)
  const activity = [
    { who: "Priya Nair",  action: "approved",  what: "Apex Logistics assessment",       when: "12 min ago",  icon: IconCheck,  tone: "good" },
    { who: "AI Engine",   action: "scored",    what: "Stellar Components Inc — 71/100", when: "1 hour ago",  icon: IconCpu,    tone: "accent" },
    { who: "Karan Mehta", action: "requested", what: "evidence for Trident Hospitality",when: "3 hours ago", icon: IconUpload, tone: "neutral" },
    { who: "System",      action: "flagged",   what: "Crestpoint Retail Chain",         when: "Yesterday",   icon: IconShield, tone: "neutral" },
    { who: "Lin Wei",     action: "completed", what: "evidence review for Bluewave",    when: "2 days ago",  icon: IconCheck,  tone: "good" },
    { who: "Admin",       action: "onboarded", what: "Vantage Microcredit as client",   when: "May 02",      icon: IconBuilding, tone: "neutral" },
  ];

  // Top tenants by average score
  const topTenants = [...tenants].sort((a, b) => b.avgScore - a.avgScore).slice(0, 4);

  return (
    <div className="hx-dash">
      <header className="hx-dash-head">
        <div>
          <div className="hx-dash-greet">{greeting}, {firstName}</div>
          <div className="hx-dash-sub">Here's what's happening across {cfg.brand.productName} today.</div>
        </div>
        <div className="hx-dash-quick">
          <Btn kind="secondary" icon={<IconBuilding size={14}/>} onClick={() => window.__nav("clients")}>Clients</Btn>
          <Btn kind="secondary" icon={<IconUsers size={14}/>}    onClick={() => window.__nav("invite-member")}>Invite member</Btn>
          <Btn kind="primary"   icon={<IconChart size={14}/>}    onClick={() => window.__nav("assessments")}>New assessment</Btn>
        </div>
      </header>

      <div className="hx-dash-stats">
        {stats.map((s, i) => (
          <StatCard key={i} label={s.label} value={s.value} delta={s.delta} deltaTone={s.tone} sub={s.sub}/>
        ))}
      </div>

      <div className="hx-dash-grid">
        <Card title="Assessments completed, last 30 days" subtitle="Daily throughput across all clients." action={<Btn kind="ghost" size="sm" iconRight={<IconChevR size={12}/>} onClick={() => window.__nav("analytics")}>View analytics</Btn>}>
          <LineChart data={days} height={200} formatValue={(v) => v.toFixed(0)} axisLabels={["30d ago", "15d ago", "Today"]}/>
        </Card>

        <Card title="Top clients" subtitle="By average credit score."
          action={<Btn kind="ghost" size="sm" iconRight={<IconChevR size={12}/>} onClick={() => window.__nav("clients")}>All clients</Btn>}>
          <div className="hx-top-models">
            {topTenants.map((t, i) => (
              <div key={t.id} className="hx-tm-row">
                <div className="hx-tm-meta">
                  <span className="hx-tm-rank">{i+1}</span>
                  <span className="hx-tm-name">{t.name}</span>
                </div>
                <div className="hx-tm-bar"><div className="hx-tm-bar-fill" style={{ width: t.avgScore + "%" }}/></div>
                <div className="hx-tm-val">{t.avgScore}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <div className="hx-dash-grid">
        <Card title="Recent activity" subtitle="Across your organization." padded={false}>
          <ul className="hx-activity">
            {activity.map((a, i) => {
              const I = a.icon;
              return (
                <li key={i} className="hx-act-row">
                  <span className={`hx-act-icon hx-act-${a.tone}`}><I size={14}/></span>
                  <span className="hx-act-text">
                    <strong>{a.who}</strong> {a.action} <span className="hx-act-what">{a.what}</span>
                  </span>
                  <span className="hx-act-when">{a.when}</span>
                </li>
              );
            })}
          </ul>
        </Card>

        <Card title="Get started" subtitle="Suggested actions to set up your project.">
          <ul className="hx-checklist">
            <ChecklistItem done text="Create your account" onClick={() => window.__nav("profile")}/>
            <ChecklistItem done text="Onboard your first client" onClick={() => window.__nav("clients")}/>
            <ChecklistItem done text="Run your first assessment" onClick={() => window.__nav("assessments")}/>
            <ChecklistItem text="Assign a consultant" onClick={() => window.__nav("consultants")}/>
            <ChecklistItem text="Invite a teammate" onClick={() => window.__nav("invite-member")}/>
            <ChecklistItem text="Review flagged assessments" onClick={() => window.__nav("assessments")}/>
          </ul>
        </Card>
      </div>

      <DashboardStyles/>
    </div>
  );
};

const ChecklistItem = ({ done, text, onClick }) => (
  <li className={`hx-cl-row ${done ? "done" : ""}`} onClick={onClick} role="button" tabIndex={0}>
    <span className="hx-cl-check">{done ? <IconCheck size={11}/> : null}</span>
    <span className="hx-cl-text">{text}</span>
    {!done && <IconChevR size={12} className="hx-cl-chev"/>}
  </li>
);

const DashboardStyles = () => (
  <style>{`
    .hx-dash { display: flex; flex-direction: column; gap: var(--gap); }
    .hx-dash-head { display: flex; justify-content: space-between; align-items: flex-end; gap: 20px; flex-wrap: wrap; }
    .hx-dash-greet { font-size: 26px; font-weight: 600; letter-spacing: -.02em; }
    .hx-dash-sub { color: var(--muted); margin-top: 4px; font-size: 14px; }
    .hx-dash-quick { display: flex; gap: 8px; flex-wrap: wrap; }

    .hx-dash-stats {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: var(--gap);
    }
    .hx-dash-stat {
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: var(--r-md);
      padding: var(--pad);
      box-shadow: var(--shadow-1);
    }
    .hx-dash-stat-label { color: var(--muted); font-size: 13px; font-weight: 500; }
    .hx-dash-stat-value { font-size: 28px; font-weight: 600; letter-spacing: -.02em; margin-top: 8px; font-feature-settings: "tnum"; line-height: 1.1; }
    .hx-dash-stat-foot { display: flex; gap: 8px; align-items: center; margin-top: 10px; flex-wrap: wrap; }
    .hx-dash-stat-sub { color: var(--muted); font-size: 12px; }

    .hx-dash-grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: var(--gap); }

    /* Bars */
    .hx-bars { display: flex; align-items: flex-end; gap: 3px; height: 180px; }
    .hx-bar {
      flex: 1;
      background: linear-gradient(to top, var(--accent), color-mix(in oklab, var(--accent) 55%, transparent));
      border-radius: 3px 3px 0 0;
      min-height: 4px;
      transition: opacity .12s;
    }
    .hx-bar:hover { opacity: .8; }
    .hx-bars-axis { display: flex; justify-content: space-between; margin-top: 8px; color: var(--muted); font-size: 11.5px; }

    /* Top models */
    .hx-top-models { display: flex; flex-direction: column; gap: 12px; }
    .hx-tm-row { display: grid; grid-template-columns: 1fr auto; gap: 6px; align-items: center; }
    .hx-tm-meta { display: flex; gap: 8px; align-items: baseline; min-width: 0; grid-column: 1 / -1; }
    .hx-tm-rank { color: var(--muted); font-size: 11.5px; font-family: var(--mono); width: 16px; }
    .hx-tm-name { font-size: 13.5px; font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .hx-tm-bar { grid-column: 1; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
    .hx-tm-bar-fill { height: 100%; background: var(--accent); border-radius: 3px; }
    .hx-tm-val { grid-column: 2; font-size: 12.5px; font-family: var(--mono); color: var(--ink-2); text-align: right; }

    /* Activity */
    .hx-activity { list-style: none; margin: 0; padding: 0; }
    .hx-act-row {
      display: flex; align-items: center; gap: 12px;
      padding: 14px 18px;
      border-bottom: 1px solid var(--line-2);
    }
    .hx-act-row:last-child { border-bottom: none; }
    .hx-act-icon { width: 30px; height: 30px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; }
    .hx-act-icon.hx-act-accent  { background: var(--accent-soft); color: var(--accent); }
    .hx-act-icon.hx-act-good    { background: var(--good-soft); color: var(--good); }
    .hx-act-icon.hx-act-neutral { background: var(--line-2); color: var(--ink-2); }
    .hx-act-text { flex: 1; font-size: 13.5px; line-height: 1.5; min-width: 0; }
    .hx-act-text strong { font-weight: 600; }
    .hx-act-what { color: var(--muted); }
    .hx-act-when { color: var(--muted); font-size: 12px; flex-shrink: 0; }

    /* Checklist */
    .hx-checklist { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
    .hx-cl-row {
      display: flex; align-items: center; gap: 12px;
      padding: 10px 12px; border-radius: 8px;
      cursor: pointer;
      transition: background .12s;
    }
    .hx-cl-row:hover { background: var(--hover); }
    .hx-cl-row:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
    .hx-cl-check {
      width: 18px; height: 18px;
      border: 1.5px solid var(--line);
      border-radius: 50%;
      display: inline-flex; align-items: center; justify-content: center;
      flex-shrink: 0; background: var(--panel);
    }
    .hx-cl-row.done .hx-cl-check { background: var(--good); border-color: var(--good); color: white; }
    .hx-cl-text { font-size: 13.5px; flex: 1; }
    .hx-cl-row.done .hx-cl-text { color: var(--muted); text-decoration: line-through; }
    .hx-cl-chev { color: var(--muted-2); }

    @media (max-width: 1180px) {
      .hx-dash-stats { grid-template-columns: repeat(2, 1fr); }
      .hx-dash-grid { grid-template-columns: 1fr; }
    }
    @media (max-width: 640px) {
      .hx-dash-greet { font-size: 22px; }
      .hx-dash-stats { grid-template-columns: 1fr; }
      .hx-bars { height: 140px; }
      .hx-dash-stat-value { font-size: 24px; }
    }
  `}</style>
);

// ---------- Product stub pages ----------
// For top-nav items that don't have full screens yet.
const ProductStubScreen = ({ name, sub, icon }) => {
  const I = icon || IconCpu;
  return (
    <div className="hx-stub">
      <div className="hx-stub-icon"><I size={28}/></div>
      <div className="hx-stub-title">{name}</div>
      <div className="hx-stub-sub">{sub || `${name} is coming soon. The shell, theming, and navigation are ready — wire your domain UI in next.`}</div>
      <div style={{display:"flex",gap:8}}>
        <Btn kind="primary" onClick={() => window.__nav("dashboard")}>Back to Dashboard</Btn>
      </div>
      <style>{`
        .hx-stub {
          display: flex; flex-direction: column; align-items: center; justify-content: center;
          gap: 16px; padding: 80px 20px; text-align: center;
          background: var(--panel); border: 1px solid var(--line);
          border-radius: var(--r-md); box-shadow: var(--shadow-1);
          min-height: 400px;
        }
        .hx-stub-icon {
          width: 64px; height: 64px; border-radius: 16px;
          background: var(--accent-soft); color: var(--accent);
          display: inline-flex; align-items: center; justify-content: center;
        }
        .hx-stub-title { font-size: 22px; font-weight: 600; letter-spacing: -.01em; }
        .hx-stub-sub { color: var(--muted); font-size: 14px; max-width: 460px; line-height: 1.5; }
      `}</style>
    </div>
  );
};

Object.assign(window, { DashboardScreen, ProductStubScreen });
