/* global React, Icon, UI, DATA */
const { useState: useDashState } = React;

function Dashboard({ navigate, toast }) {
  const { Button, StatusBadge, CategoryChip, Stat } = UI;
  const D = DATA;
  const [prompt, setPrompt] = useDashState("");
  const recentProjects = D.projects.filter((p) => p.status !== "draft").slice(0, 3);
  const recentExec = D.executions.slice(0, 6);

  const quick = [
    { icon: "plus", label: "Create a project", sub: "Start from scratch", go: () => navigate("createProject"), accent: true },
    { icon: "store", label: "Clone from marketplace", sub: "12 prebuilt workflows", go: () => navigate("marketplace") },
    { icon: "link", label: "Connect a source", sub: "Gmail, Drive, database", go: () => navigate("connectors") },
  ];

  return (
    <div className="app-scroll">
      <div className="page fade-in">
        {/* greeting */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 22 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Monday · 8 June 2026</div>
            <h2 style={{ fontSize: 30 }}>Good afternoon, Tom</h2>
          </div>
          <div className="muted" style={{ fontSize: 13.5, textAlign: "right" }}>
            <span style={{ color: "var(--ef-fg-1)", fontWeight: 700 }}>2,937</span> executions this month
          </div>
        </div>

        {/* hero band */}
        <div className="card" style={{ padding: 24, marginBottom: 24, background: "var(--ef-ink-950)", border: 0, color: "var(--ef-bone)", overflow: "hidden", position: "relative" }}>
          <h3 style={{ color: "var(--ef-bone)", fontSize: 24, maxWidth: 620 }}>What document workflow do you want to automate?</h3>
          <div style={{ display: "flex", gap: 10, marginTop: 18, maxWidth: 760 }}>
            <div style={{ flex: 1, position: "relative" }}>
              <span style={{ position: "absolute", left: 14, top: 14 }}><Icon name="sparkles" size={18} color="var(--ef-beam-500)" /></span>
              <input value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder="Describe one — e.g. Extract purchase orders and send them to ERP"
                style={{ width: "100%", height: 48, background: "var(--ef-ink-900)", border: "1px solid var(--ef-ink-700)", borderRadius: 8, color: "var(--ef-bone)", padding: "0 16px 0 42px", fontSize: 14.5, outline: "none" }} />
            </div>
            <button className="btn btn-accent btn-lg" onClick={() => { toast("Assistant draft coming in a future release", "info"); }}>
              <Icon name="sparkles" size={16} /> Generate
            </button>
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 14, flexWrap: "wrap" }}>
            {["Translate incoming contracts to English", "Split every uploaded PDF into pages", "Detect duplicate invoices"].map((s) => (
              <button key={s} onClick={() => setPrompt(s)} style={{ background: "var(--ef-ink-900)", border: "1px solid var(--ef-ink-800)", color: "var(--ef-ink-300)", borderRadius: 999, padding: "6px 13px", fontSize: 12.5, fontWeight: 600 }}>{s}</button>
            ))}
          </div>
        </div>

        {/* quick actions */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 28 }}>
          {quick.map((q) => (
            <button key={q.label} onClick={q.go} className="card card-hover" style={{ padding: 18, textAlign: "left", display: "flex", flexDirection: "column", gap: 12, alignItems: "flex-start" }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: q.accent ? "var(--ef-beam-500)" : "var(--ef-bone-2)", border: q.accent ? 0 : "1px solid var(--ef-border)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <Icon name={q.icon} size={20} color={q.accent ? "var(--ef-ink-950)" : "var(--ef-fg-2)"} />
              </div>
              <div>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ef-fg-1)" }}>{q.label}</div>
                <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{q.sub}</div>
              </div>
            </button>
          ))}
        </div>

        {/* recent projects */}
        <SectionTitle title="Recent projects" action={{ label: "All projects", go: () => navigate("projects") }} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, marginBottom: 30 }}>
          {recentProjects.map((p) => (
            <div key={p.id} className="card card-hover" style={{ padding: 18 }} onClick={() => navigate("project", { id: p.id })}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
                <CategoryChip category={p.category} />
                <StatusBadge status={p.status} />
              </div>
              <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ef-fg-1)", letterSpacing: "-0.01em" }}>{p.name}</div>
              <p className="muted" style={{ fontSize: 13, marginTop: 6, lineHeight: 1.45, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", minHeight: 38 }}>{p.description}</p>
              <div className="divider" style={{ margin: "14px 0 12px" }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                  {p.lastStatus && <StatusBadge status={p.lastStatus} dot={true} size="sm" />}
                </div>
                <span className="muted mono" style={{ fontSize: 11.5 }}>{D.fmtAgo(p.lastRun)}</span>
              </div>
            </div>
          ))}
        </div>

        {/* recent executions */}
        <div className="card">
          <CardHead title="Recent executions" action={{ label: "View all", go: () => navigate("executions") }} />
          <table className="tbl">
            <thead><tr><th>Execution</th><th>Workflow</th><th>Status</th><th style={{ textAlign: "right" }}>Files</th><th style={{ textAlign: "right" }}>When</th></tr></thead>
            <tbody>
              {recentExec.map((e) => (
                <tr key={e.id} className="tbl-row" onClick={() => navigate("execution", { id: e.id })}>
                  <td className="mono" style={{ color: "var(--ef-fg-1)", fontWeight: 600, fontSize: 12.5 }}>{e.id}</td>
                  <td style={{ maxWidth: 260, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.projectName}</td>
                  <td><StatusBadge status={e.status} /></td>
                  <td style={{ textAlign: "right" }} className="tabular">{e.files}{e.failed ? <span style={{ color: "var(--ef-danger)" }}> · {e.failed} failed</span> : ""}</td>
                  <td style={{ textAlign: "right" }} className="muted mono">{D.fmtAgo(e.started)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function SectionTitle({ title, action }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
      <h5 style={{ fontSize: 17 }}>{title}</h5>
      {action && <span className="link" style={{ fontSize: 13, fontWeight: 700, textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 5 }} onClick={action.go}>{action.label} <Icon name="arrow-right" size={14} /></span>}
    </div>
  );
}
function CardHead({ title, action }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "15px 18px", borderBottom: "1px solid var(--ef-border)" }}>
      <h6 style={{ fontSize: 14.5 }}>{title}</h6>
      {action && <span className="link" style={{ fontSize: 12.5, fontWeight: 700, textDecoration: "none" }} onClick={action.go}>{action.label}</span>}
    </div>
  );
}
function TriggerLabel({ t }) {
  const map = { file_uploaded: "On file upload", email_received: "On email", scheduled: "Scheduled", manual: "Manual", api_request: "Via API", webhook: "Via webhook", folder_updated: "On folder update" };
  return <span>{map[t] || t}</span>;
}

window.Dashboard = Dashboard;
window.DashHelpers = { SectionTitle, CardHead, TriggerLabel };
