// Owner dashboard cards
const Spark = ({ data, color = "var(--accent)" }) => {
  if (!data || !data.length) return null;
  const w = 200, h = 28;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const step = w / (data.length - 1);
  const pts = data.map((v, i) => `${i * step},${h - ((v - min) / range) * (h - 4) - 2}`).join(" ");
  const area = `0,${h} ${pts} ${w},${h}`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className="spark">
      <polygon points={area} fill={color} fillOpacity="0.08" />
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.25" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
};

// Calm first-run placeholder — a few skeleton lines + a reassuring note.
const Empty = ({ lines = 3, note }) => (
  <div className="card-empty">
    <div className="card-empty-rows">
      {Array.from({ length: lines }).map((_, i) => (
        <div key={i} className="ce-row">
          <div className="ce-dot" />
          <div className="ce-bar" style={{ width: `${78 - i * 16}%` }} />
        </div>
      ))}
    </div>
    {note && <div className="card-empty-note">{note}</div>}
  </div>
);

// Persistent "you're always in control" reassurance cue.
const Reassure = ({ className = "" }) => (
  <div className={"reassure " + className}>
    <Ic.Undo size={12} />
    <span>You're always in control — E28E never sends without your yes. Review and undo anything.</span>
  </div>
);

// The curated channel set a local service business actually uses daily.
const CH_ICON = { email: Ic.Mail, phone: Ic.Phone, text: Ic.Text, ig: Ic.Instagram, fb: Ic.Facebook, google: Ic.Store };
const ChIcon = ({ ch, size = 12 }) => { const I = CH_ICON[ch] || Ic.Mail; return <I size={size} />; };

// "While you slept" — headline is a COUNT of real actions; each dollar is
// labeled by category. Rows are doorways into the underlying surface.
const RecapHero = ({ d, name, day, onNavigate }) => {
  if (day === "day1") {
    return (
      <div className="recap recap-empty">
        <div className="recap-lead-wrap">
          <div className="recap-eyebrow"><Ic.Sparkle size={12} /> Your first day on E28E</div>
          <h2 className="recap-lead recap-lead-muted">
            E28E is still learning <span className="accent">{name}</span>.
          </h2>
          <p className="recap-sub">
            Tell the assistant about your business and connect your inbox — within a day, this strip
            shows the work E28E handled for you, counted honestly and labeled by category.
          </p>
        </div>
        <div className="recap-empty-meter">
          <div className="recap-empty-meter-label">Actions handled this week</div>
          <div className="recap-empty-meter-val">0<small>so far</small></div>
        </div>
      </div>
    );
  }
  const r = d.recap;
  return (
    <div className="recap">
      <div className="recap-lead-wrap">
        <div className="recap-eyebrow"><Ic.Sparkle size={12} /> While you slept · this week</div>
        <h2 className="recap-lead">
          E28E handled <span className="accent">{r.actionCount} things</span> for you.
        </h2>
        <p className="recap-sub">Every action is real. Here's what each is worth — labeled by category, nothing rounded up into money you haven't earned.</p>
        <div className="recap-legend">
          <span><span className="recap-legend-sw" data-tone="accent" /> Pipeline &amp; drafts — potential, not yet banked</span>
          <span><span className="recap-legend-sw" data-tone="warn" /> At risk — money to recover</span>
        </div>
      </div>
      <div className="recap-items">
        {r.items.map((it, i) => (
          <button key={i} className="recap-item" onClick={() => onNavigate && onNavigate(it.target)}>
            <span className="recap-item-did">{it.did}</span>
            <span className="recap-item-arrow">→ {it.outcome}</span>
            <span className="recap-item-val" data-tone={it.tone}>
              {it.amount}<small>{it.cat}</small>
            </span>
            <Ic.Chevron size={13} className="recap-item-chev" />
          </button>
        ))}
      </div>
    </div>
  );
};

// Approvals — "3 things need your yes". One-tap decide; AI did the labor.
const ApprovalsCard = ({ d, day }) => {
  const [resolved, setResolved] = React.useState({});
  const items = day === "day1" ? [] : d.approvals;
  const pending = items.filter((it) => !resolved[it.id]);
  const resolve = (id, verb) => setResolved((r) => ({ ...r, [id]: verb }));

  return (
    <div className="card col-6 card-approvals" id="card-approvals">
      <div className="card-head">
        <div className="card-title card-title-strong">
          <Ic.Shield /> {pending.length > 0 ? `${pending.length} things need your yes` : "Nothing needs your yes"}
        </div>
        <Reassure className="reassure-inline" />
      </div>

      {day === "day1" ? (
        <Empty lines={2} note="When E28E wants to send something on your behalf, it waits here for your okay. Nothing goes out until you decide." />
      ) : pending.length === 0 ? (
        <div className="approvals-clear">
          <Ic.Check size={16} />
          <span>All caught up. E28E will hold the next thing here for your okay.</span>
        </div>
      ) : (
        <div className="approvals-list">
          {items.map((it) => {
            const Icon = Ic[it.icon] || Ic.Sparkle;
            const state = resolved[it.id];
            return (
              <div key={it.id} className="approval" data-resolved={state || ""}>
                <div className="approval-icon"><Icon size={15} /></div>
                <div className="approval-body">
                  <div className="approval-title">
                    {it.title}
                    {it.amount && <span className="approval-amount">{it.amount}</span>}
                  </div>
                  <div className="approval-detail">{it.detail}</div>
                </div>
                {state ? (
                  <div className="approval-done" data-verb={state}>
                    {state === "approved" ? <><Ic.Check size={12} /> Approved · sent</> : <>Dismissed</>}
                    <button className="approval-undo" onClick={() => resolve(it.id, null)}><Ic.Undo size={11} /> Undo</button>
                  </div>
                ) : (
                  <div className="approval-actions">
                    <button className="btn approve" onClick={() => resolve(it.id, "approved")}><Ic.Check size={12} /> Approve</button>
                    <button className="btn ghost dismiss" onClick={() => resolve(it.id, "dismissed")}>Dismiss</button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

// Day 1 — channels shown as honest "connect" states, not pre-filled DMs.
const InboxConnect = ({ d }) => {
  const channels = (d && d.connectChannels) || window.DATA.connectChannels;
  return (
    <div className="connect-block">
      <div className="connect-list">
        {channels.map((c) => (
          <div key={c.ch} className="connect-row">
            <div className="inbox-channel" data-ch={c.ch}><ChIcon ch={c.ch} /></div>
            <div className="connect-body">
              <div className="connect-name">{c.name}</div>
              <div className="connect-note">{c.desc}</div>
              {c.req && <div className="connect-req">{c.req}</div>}
            </div>
            <button className="btn connect-btn">Connect</button>
          </div>
        ))}
      </div>
      <div className="inbox-foot">
        <Ic.Shield size={11} />
        <span>Instagram &amp; Facebook connect as <strong>Business accounts</strong> only — never your personal inbox.</span>
      </div>
    </div>
  );
};

const InboxCard = ({ d, day }) => {
  const [state, setState] = React.useState("all");
  const needs = d.inbox.filter(i => i.needsReply);
  const items = state === "needs" ? needs : d.inbox;
  // Display strip = the breadth of channels E28E unifies, all connected.
  const STRIP = d.channels;
  return (
    <div className="card col-4" id="card-inbox">
      <div className="card-head">
        <div className="card-title"><Ic.Inbox /> Communications</div>
        <button className="card-action" data-nav="inbox">Add channel <Ic.Plus size={12} /></button>
      </div>
      {day === "day1" ? (
        <InboxConnect d={d} />
      ) : (
      <>
      <div className="ch-strip">
        <div className="ch-strip-icons">
          {STRIP.map(c => (
            <span key={c.ch} className="ch-chip" data-ch={c.ch} title={`${c.title} · connected`}>
              <ChIcon ch={c.ch} size={12} />
              <span className="ch-chip-name">{c.label}</span>
              <span className="ch-chip-ok"><Ic.Check size={9} /></span>
            </span>
          ))}
        </div>
        <div className="ch-strip-note">
          <Ic.Check size={11} /> All six channels connected — every way your customers reach you, answered in one place.
        </div>
      </div>
      <div className="inbox-subhead">
        <span className="inbox-subhead-title">Unified inbox</span>
        <div className="inbox-statefilter">
          <button data-active={state === "all"} onClick={() => setState("all")}>All <span className="sf-count">{d.inbox.length}</span></button>
          <button data-active={state === "needs"} onClick={() => setState("needs")}>Needs reply <span className="sf-count">{needs.length}</span></button>
        </div>
      </div>
      <div className="inbox-list">
        {items.map(i => (
          <div key={i.id} className={"inbox-item" + (i.unread ? " unread" : "")}>
            <div className="inbox-channel" data-ch={i.channel}><ChIcon ch={i.channel} /></div>
            <div>
              <div className="inbox-name">
                {i.name}
                {i.ai && <span className="inbox-ai-tag"><Ic.Sparkle size={9} /> {i.aiLabel || "AI drafted reply"}</span>}
                {i.transcribed && <span className="inbox-tag-muted"><Ic.Text size={9} /> Transcribed</span>}
                {i.flag && <span className="inbox-flag">{i.flag}</span>}
              </div>
              <div className="inbox-snippet">{i.snippet}</div>
              {i.suggested && (
                <div className="inbox-suggest">
                  <Ic.Undo size={10} /> AI reply ready: <span className="inbox-suggest-text">{i.suggested}</span>
                </div>
              )}
            </div>
            <div className="inbox-time">{i.time}</div>
          </div>
        ))}
      </div>
      <div className="inbox-foot">
        <Ic.Shield size={11} />
        <span>Instagram &amp; Facebook are linked as <strong>Business accounts</strong> — never your personal inbox.</span>
      </div>
      </>
      )}
    </div>
  );
};

const TodayCard = ({ d, day }) => (
  <div className="card col-3">
    <div className="card-head">
      <div className="card-title"><Ic.Calendar /> Today's schedule</div>
      <button className="card-action">Wed, May 6 <Ic.Chevron size={12} /></button>
    </div>
    {day === "day1" ? (
      <Empty lines={3} note="Your calendar and crew dispatches will show here once E28E is connected to your schedule." />
    ) : (
    <div>
      {d.today.map((t, i) => (
        <div key={i} className="day">
          <div className="day-time">{t.time}</div>
          <div>
            <div className="day-title"><span className={`pill ${t.tone}`}>{t.pill}</span>{t.title}</div>
            <div className="day-sub">{t.sub}</div>
          </div>
        </div>
      ))}
    </div>
    )}
  </div>
);

const AgentsCard = ({ d, day }) => (
  <div className="card col-2">
    <div className="card-head">
      <div className="card-title"><Ic.Bot /> AI Agents</div>
      <button className="card-action" data-nav="agents">Manage <Ic.Chevron size={12} /></button>
    </div>
    {day === "day1" ? (
      <Empty lines={2} note="E28E sets up agents for you as it learns the work — leads, quotes, scheduling." />
    ) : (
    <div>
      {d.agents.map((a, i) => (
        <div key={i} className="agent">
          <div className="agent-mark">
            {a.name.split(" ").map(w => w[0]).slice(0, 2).join("")}
            <span className="pulse" data-state={a.state}></span>
          </div>
          <div>
            <div className="agent-name">{a.name}</div>
            <div className="agent-task">{a.task}</div>
          </div>
          <div className="agent-stat">{a.today > 0 ? `${a.today} today` : "—"}</div>
        </div>
      ))}
    </div>
    )}
  </div>
);

const FinancesCard = ({ d, day }) => {
  const total = d.finances.breakdown.reduce((s, x) => s + x.value, 0);
  return (
    <div className="card col-3" id="card-finances">
      <div className="card-head">
        <div className="card-title"><Ic.Coin /> Finances</div>
        <button className="card-action" data-nav="finances">May <Ic.Chevron size={12} /></button>
      </div>
      {day === "day1" ? (
        <Empty lines={3} note="Connect your payment account and your revenue, profit, and unpaid invoices appear here automatically." />
      ) : (
      <>
      <div className="fin-row">
        <div className="fin-stat"><div className="v">${(d.finances.mtd / 1000).toFixed(1)}k</div><div className="l">Revenue MTD</div></div>
        <div className="fin-stat"><div className="v">${(d.finances.profit / 1000).toFixed(1)}k</div><div className="l">Net profit</div></div>
      </div>
      <div className="fin-bar">
        {d.finances.breakdown.map((b, i) => (
          <div key={i} className="fin-seg" style={{ width: `${(b.value / total) * 100}%`, background: b.color }} />
        ))}
      </div>
      <div className="fin-legend">
        {d.finances.breakdown.map((b, i) => (
          <span key={i}><span className="sw" style={{ background: b.color }}></span>{b.label} {b.value}%</span>
        ))}
      </div>
      <hr className="hr" />
      <div className="fin-row">
        <div className="fin-stat"><div className="v" style={{ fontSize: 18 }}>${(d.finances.arOpen / 1000).toFixed(1)}k</div><div className="l">A/R open</div></div>
        <div className="fin-stat"><div className="v" style={{ fontSize: 18, color: "var(--warn)" }}>${(d.finances.arOverdue / 1000).toFixed(1)}k</div><div className="l">Overdue</div></div>
      </div>
      </>
      )}
    </div>
  );
};

const ProjectsCard = ({ d, day }) => (
  <div className="card col-4">
    <div className="card-head">
      <div className="card-title"><Ic.Folder /> Active projects</div>
      <button className="card-action" data-nav="projects">All <Ic.Chevron size={12} /></button>
    </div>
    {day === "day1" ? (
      <Empty lines={3} note="Add your first job and E28E tracks progress, crew, and due dates for you." />
    ) : (
    <div>
      {d.projects.map((p, i) => (
        <div key={i} className="proj">
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="proj-title">{p.name}</div>
            <div className="proj-meta">{p.client} · due {p.due}</div>
          </div>
          <div className="proj-stack">
            {p.crew.map((c, j) => <div key={j} className="av">{c}</div>)}
          </div>
          <div style={{ width: 60 }}>
            <div className="proj-progress"><div style={{ width: `${p.pct}%` }} /></div>
          </div>
          <div className="proj-pct">{p.pct}%</div>
        </div>
      ))}
    </div>
    )}
  </div>
);

// Automations, in plain English — no flow diagrams, no vendor chains.
const AutomationsCard = ({ d, day }) => (
  <div className="card col-4">
    <div className="card-head">
      <div className="card-title"><Ic.Sparkle /> Automations E28E runs for you</div>
      <button className="card-action" data-nav="workflows">Manage <Ic.Chevron size={12} /></button>
    </div>
    {day === "day1" ? (
      <Empty lines={2} note="As E28E learns your routine, it suggests small jobs it can handle for you — each one in plain English, always switch-off-able." />
    ) : (
    <div className="auto-list">
      {d.workflows.filter(w => w.on).map((w, i) => (
        <div key={i} className="auto">
          <span className="auto-dot" />
          <div>
            <div className="auto-name">{w.name}</div>
            <div className="auto-plain">{w.plain}</div>
          </div>
        </div>
      ))}
      <div className="auto-foot">Running quietly in the background. <a className="tiny-link">Turn any off in Settings →</a></div>
    </div>
    )}
  </div>
);

// Integrations reframed as quiet reassurance — connected, watched, low-priority.
const ConnectedCard = ({ d, day }) => {
  const on = d.integrations.filter(i => i.on);
  return (
    <div className="card col-2 card-connected">
      <div className="card-head">
        <div className="card-title card-title-quiet"><Ic.Check /> Connected</div>
      </div>
      {day === "day1" ? (
        <div className="connected-note">Connect your tools once — E28E keeps an eye on them for you after that.</div>
      ) : (
      <>
        <div className="connected-note">E28E is watching these for you — no action needed.</div>
        <div className="connected-list">
          {on.map((it, i) => <span key={i} className="connected-chip">{it.name}</span>)}
        </div>
      </>
      )}
    </div>
  );
};

// Inventory is optional / per-vertical — not a default headline card.
const InventoryCard = ({ d, day }) => (
  <div className="card col-6">
    <div className="card-head">
      <div className="card-title"><Ic.Box /> Inventory <span className="card-optional">optional · for stock-based businesses</span></div>
      <button className="card-action" data-nav="inventory">Manage <Ic.Chevron size={12} /></button>
    </div>
    {day === "day1" ? (
      <Empty lines={2} note="Track materials only if your business carries stock. E28E reorders low items for your okay." />
    ) : (
    <div className="inv-grid">
      {d.inventory.map((it, i) => {
        const cls = it.state === "low" ? "low" : it.state === "empty" ? "empty" : "";
        return (
          <div key={i} className="inv-row">
            <div className="inv-name">{it.name}</div>
            <div className={`inv-bar ${cls}`}>
              <div style={{ width: `${(it.qty / it.max) * 100}%` }} />
            </div>
            <div className="inv-qty">{it.qty}/{it.max}</div>
          </div>
        );
      })}
    </div>
    )}
  </div>
);

const EmployeesCard = ({ d, day }) => (
  <div className="card col-2">
    <div className="card-head">
      <div className="card-title"><Ic.Users /> Team</div>
      <button className="card-action" data-nav="employees">View all <Ic.Chevron size={12} /></button>
    </div>
    {day === "day1" ? (
      <Empty lines={2} note="Invite your crew and E28E gives each person their own scoped view." />
    ) : (
    <div className="emp-grid">
      {d.employees.map((e, i) => (
        <div key={i} className="emp">
          <div className="emp-av">
            {e.initials}
            <span className="status" data-s={e.status}></span>
          </div>
          <div>
            <div className="emp-name">{e.name}</div>
            <div className="emp-role">{e.role}</div>
          </div>
        </div>
      ))}
    </div>
    )}
  </div>
);

window.OwnerCards = { RecapHero, ApprovalsCard, Reassure, InboxCard, TodayCard, AgentsCard, FinancesCard, ProjectsCard, AutomationsCard, ConnectedCard, InventoryCard, EmployeesCard };
