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

// Reusable horizontal flow representation (input → processing → output)
function FlowStrip({ steps, compact }) {
  const { NODE_TYPES } = UI;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap" }}>
      {steps.map((s, i) => {
        const m = NODE_TYPES[s.type] || NODE_TYPES.processing;
        return (
          <React.Fragment key={i}>
            <div style={{ display: "flex", alignItems: "center", gap: 7, padding: compact ? "5px 9px" : "7px 12px", background: "var(--ef-bg-raised)", border: "1px solid var(--ef-border)", borderRadius: 8 }}>
              <span style={{ width: 7, height: 7, borderRadius: 999, background: m.color }} />
              <Icon name={m.icon} size={compact ? 13 : 15} color="var(--ef-fg-3)" />
              <span style={{ fontSize: compact ? 11.5 : 12.5, fontWeight: 600, color: "var(--ef-fg-1)", whiteSpace: "nowrap" }}>{s.label}</span>
            </div>
            {i < steps.length - 1 && <Icon name="chevron-right" size={14} color="var(--ef-fg-4)" />}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// --------------------------- Projects list ---------------------------
function ProjectsList({ navigate }) {
  const { Button, StatusBadge, CategoryChip, EmptyState } = UI;
  const [q, setQ] = usePState("");
  const [status, setStatus] = usePState("all");
  const [view, setView] = usePState("cards");
  const D = DATA;

  let list = D.projects.filter((p) => (status === "all" || p.status === status) && p.name.toLowerCase().includes(q.toLowerCase()));

  const statuses = ["all", "active", "paused", "draft", "archived"];

  return (
    <div className="app-scroll"><div className="page fade-in">
      <UI.PageHeader title="Projects" subtitle="Each project automates one type of document. Build a workflow, configure it once, and let executions run."
        actions={<>
          <Button variant="secondary" icon="store" onClick={() => navigate("marketplace")}>Clone from marketplace</Button>
          <Button variant="primary" icon="plus" onClick={() => navigate("createProject")}>Create project</Button>
        </>} />

      <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 20, flexWrap: "wrap" }}>
        <div style={{ position: "relative", flex: 1, minWidth: 220, maxWidth: 360 }}>
          <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)" }}><Icon name="search" size={16} color="var(--ef-fg-4)" /></span>
          <input className="input" placeholder="Search projects" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 36 }} />
        </div>
        <div className="seg">
          {statuses.map((s) => <button key={s} className={status === s ? "active" : ""} onClick={() => setStatus(s)} style={{ textTransform: "capitalize" }}>{s}</button>)}
        </div>
        <div style={{ flex: 1 }} />
        <div className="seg">
          <button className={view === "cards" ? "active" : ""} onClick={() => setView("cards")}><Icon name="layout-dashboard" size={15} /></button>
          <button className={view === "table" ? "active" : ""} onClick={() => setView("table")}><Icon name="rows" size={15} /></button>
        </div>
      </div>

      {list.length === 0 ? (
        <div className="card"><EmptyState icon="folder" title="No projects match" body="Try a different search or status filter." /></div>
      ) : view === "cards" ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(330px, 1fr))", gap: 16 }}>
          {list.map((p) => (
            <div key={p.id} className="card card-hover" style={{ padding: 20 }} 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: 17, fontWeight: 700, color: "var(--ef-fg-1)", letterSpacing: "-0.01em" }}>{p.name}</div>
              <p className="muted" style={{ fontSize: 13, marginTop: 6, lineHeight: 1.45, minHeight: 56, display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{p.description}</p>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", margin: "12px 0 14px" }}>
                {p.inputs.slice(0, 2).map((s) => <span key={s} className="badge" style={{ fontSize: 11 }}><Icon name="inbox" size={12} color="var(--ef-fg-4)" />{s}</span>)}
                {p.outputs.slice(0, 2).map((s) => <span key={s} className="badge" style={{ fontSize: 11 }}><Icon name="send" size={12} color="var(--ef-fg-4)" />{s}</span>)}
              </div>
              <div className="divider" style={{ marginBottom: 12 }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span className="muted" style={{ fontSize: 12 }}><span className="mono tabular" style={{ color: "var(--ef-fg-1)", fontWeight: 600 }}>{p.executions.toLocaleString()}</span> runs</span>
                {p.lastStatus ? <StatusBadge status={p.lastStatus} size="sm" /> : <span className="muted" style={{ fontSize: 12 }}>Not run yet</span>}
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="card" style={{ overflow: "hidden" }}>
          <table className="tbl">
            <thead><tr><th>Project</th><th>Category</th><th>Status</th><th>Trigger</th><th style={{ textAlign: "right" }}>Runs</th><th>Last run</th><th></th></tr></thead>
            <tbody>
              {list.map((p) => (
                <tr key={p.id} className="tbl-row" onClick={() => navigate("project", { id: p.id })}>
                  <td><div style={{ fontWeight: 700, color: "var(--ef-fg-1)" }}>{p.name}</div></td>
                  <td><CategoryChip category={p.category} /></td>
                  <td><StatusBadge status={p.status} /></td>
                  <td className="muted"><TriggerText t={p.trigger} /></td>
                  <td style={{ textAlign: "right" }} className="tabular">{p.executions.toLocaleString()}</td>
                  <td className="muted mono" style={{ fontSize: 12 }}>{D.fmtAgo(p.lastRun)}</td>
                  <td><Icon name="chevron-right" size={16} color="var(--ef-fg-4)" /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div></div>
  );
}

function TriggerText({ t }) {
  const map = { file_uploaded: "On file upload", email_received: "On email", scheduled: "Scheduled", manual: "Manual", api_request: "Via API", webhook: "Via webhook" };
  return <span>{map[t] || t}</span>;
}

// --------------------------- Create project wizard ---------------------------
function CreateProjectWizard({ navigate, toast }) {
  const [step, setStep] = usePState(0);
  const [sub, setSub] = usePState(0);
  const t = window.useTemplateData("");
  const [d, setD] = usePState({
    name: "", description: "", category: "Manufacturing", start: "scratch",
    input: "File upload", processing: ["Extract fields", "Select fields", "Convert PDF to Excel"], output: "Google Drive",
    activate: "file_uploaded",
  });
  const set = (k, v) => setD((s) => ({ ...s, [k]: v }));
  const steps = ["Basics", "Start method", "Input", "Processing", "Output", "Configuration", "Test run", "Activate"];
  const last = step === steps.length - 1;
  const CONFIG_STEP = 5;
  const canNext = step === CONFIG_STEP
    ? window.templateCanNext(sub, t, false)
    : [d.name.trim().length > 1, !!d.start, !!d.input, d.processing.length > 0, !!d.output, true, true, true][step];
  const goBack = () => { if (step === CONFIG_STEP && sub > 0) setSub((s) => s - 1); else setStep((s) => s - 1); };
  const goNext = () => {
    if (step === CONFIG_STEP && sub < window.TEMPLATE_SUB_STEPS.length - 1) { setSub((s) => s + 1); return; }
    if (last) { toast("Project created", "success"); navigate("project", { id: "proj_po" }); return; }
    setStep((s) => s + 1);
  };

  const Card = ({ active, onClick, icon, title, sub, soon }) => (
    <button onClick={soon ? undefined : onClick} className="card" disabled={soon} style={{
      textAlign: "left", padding: 16, display: "flex", gap: 13, alignItems: "flex-start", cursor: soon ? "not-allowed" : "pointer",
      borderColor: active ? "var(--ef-ink-950)" : "var(--ef-border)", background: active ? "var(--ef-bone-2)" : "var(--ef-bg-raised)", opacity: soon ? 0.55 : 1,
    }}>
      <div style={{ width: 38, height: 38, borderRadius: 9, background: active ? "var(--ef-ink-950)" : "var(--ef-bone-2)", border: active ? 0 : "1px solid var(--ef-border)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        <Icon name={icon} size={19} color={active ? "var(--ef-beam-500)" : "var(--ef-fg-3)"} /></div>
      <div><div style={{ fontSize: 14, fontWeight: 700, color: "var(--ef-fg-1)", display: "flex", gap: 8, alignItems: "center" }}>{title}{soon && <span className="badge" style={{ fontSize: 10 }}>Soon</span>}</div>
        <div className="muted" style={{ fontSize: 12.5, marginTop: 3, lineHeight: 1.4 }}>{sub}</div></div>
    </button>
  );
  const Multi = ({ options, value, k }) => (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
      {options.map((o) => { const sel = value.includes(o); return (
        <button key={o} className={`chip ${sel ? "selected" : ""}`} onClick={() => set(k, sel ? value.filter((x) => x !== o) : [...value, o])}>
          {sel && <Icon name="check" size={13} color="var(--ef-bone)" />}{o}</button>); })}
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100vh", width: "100vw", background: "var(--ef-bg)" }}>
      <div style={{ padding: "14px 28px", borderBottom: "1px solid var(--ef-border)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <button className="btn btn-ghost btn-sm" onClick={() => navigate("projects")}><Icon name="x" size={16} /></button>
          <span style={{ fontWeight: 800, fontSize: 16 }}>Create project</span>
        </div>
        <div style={{ flex: 1, maxWidth: 720, margin: "0 32px" }}><UI.Stepper steps={steps} current={step} /></div>
        <div style={{ width: 80 }} />
      </div>

      <div style={{ flex: 1, overflowY: "auto" }}>
        <div style={{ maxWidth: step === CONFIG_STEP ? 1000 : 720, margin: "0 auto", padding: "36px 24px 60px" }} className="fade-in" key={step}>
          {step === 0 && (<div>
            <h2 style={{ fontSize: 30 }}>Project basics</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 26 }}>Give your project a clear name. Examples: Purchase order processing, Invoice automation, Bank statement analysis.</p>
            <UI.Field label="Project name" required><input className="input" autoFocus placeholder="e.g. Purchase order processing" value={d.name} onChange={(e) => set("name", e.target.value)} style={{ height: 46 }} /></UI.Field>
            <UI.Field label="Description" help="Visible to your team on the project page."><textarea className="textarea" placeholder="What documents does this project handle, and what should happen to them?" value={d.description} onChange={(e) => set("description", e.target.value)} /></UI.Field>
            <UI.Field label="Category"><select className="select" value={d.category} onChange={(e) => set("category", e.target.value)} style={{ maxWidth: 280 }}>{Object.keys(UI.CATEGORY).map((c) => <option key={c}>{c}</option>)}</select></UI.Field>
          </div>)}

          {step === 1 && (<div>
            <h2 style={{ fontSize: 30 }}>How do you want to start?</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 26 }}>Build from scratch, or start from something that already works.</p>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Card active={d.start === "scratch"} onClick={() => set("start", "scratch")} icon="git-branch" title="Build from scratch" sub="Open a blank workflow builder and add nodes." />
              <Card active={d.start === "clone"} onClick={() => set("start", "clone")} icon="store" title="Clone from marketplace" sub="Start from a prebuilt workflow with mappings." />
              <Card active={d.start === "sample"} onClick={() => set("start", "sample")} icon="upload-cloud" title="Start from a sample document" sub="Upload an example and we'll suggest the workflow." />
              <Card icon="sparkles" title="Describe in natural language" sub="Tell the assistant the outcome you want." soon />
            </div>
          </div>)}

          {step === 2 && (<div>
            <h2 style={{ fontSize: 30 }}>Where do documents come from?</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 26 }}>Choose the input source that triggers this workflow.</p>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
              <Card active={d.input === "File upload"} onClick={() => set("input", "File upload")} icon="upload-cloud" title="File upload" sub="Drag-and-drop or batch upload." />
              <Card active={d.input === "Gmail"} onClick={() => set("input", "Gmail")} icon="mail" title="Gmail" sub="Read matching email attachments." />
              <Card active={d.input === "Google Drive"} onClick={() => set("input", "Google Drive")} icon="hard-drive" title="Google Drive" sub="Monitor a folder for new files." />
              <Card icon="mail" title="Outlook" sub="Read Outlook attachments." soon />
              <Card icon="webhook" title="API" sub="Receive documents via API." soon />
              <Card icon="database" title="Database" sub="Poll records or file columns." soon />
            </div>
          </div>)}

          {step === 3 && (<div>
            <h2 style={{ fontSize: 30 }}>What should happen to the documents?</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 26 }}>Pick one or more processing goals. You'll arrange the exact steps in the builder.</p>
            <Multi k="processing" value={d.processing} options={["Extract fields", "Select fields", "Convert PDF to Excel", "Translate document", "Summarize document", "Split pages", "Create presentation", "Detect duplicates", "Consolidate documents", "Generate Word", "Transform PDF layout", "Custom"]} />
          </div>)}

          {step === 4 && (<div>
            <h2 style={{ fontSize: 30 }}>Where should outputs go?</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 8 }}>Generating a file (CSV, Excel, Word) is a processing step. The output is where the result is delivered.</p>
            <div className="badge" style={{ marginBottom: 24, background: "var(--ef-beam-100)", color: "var(--ef-beam-700)", border: 0 }}><Icon name="info" size={13} color="var(--ef-beam-700)" /> Export-to-file is processing · delivery is output</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
              <Card active={d.output === "Download"} onClick={() => set("output", "Download")} icon="download" title="Downloadable file" sub="Available in the project outputs." />
              <Card active={d.output === "Email"} onClick={() => set("output", "Email")} icon="send" title="Email" sub="Send files or a report." />
              <Card active={d.output === "Google Drive"} onClick={() => set("output", "Google Drive")} icon="hard-drive" title="Google Drive" sub="Upload to a Drive folder." />
              <Card icon="database" title="Database" sub="Insert extracted records." soon />
              <Card icon="webhook" title="API / ERP" sub="POST structured data." soon />
              <Card icon="webhook" title="Webhook" sub="Notify another system." soon />
            </div>
          </div>)}

          {step === CONFIG_STEP && (<div>
            <h2 style={{ fontSize: 30 }}>Configuration</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 22 }}>Many document types repeat with the same layout. Configure once here, and every future document reuses your field selection, format, and mapping.</p>
            <div className="card" style={{ overflow: "hidden" }}>
              <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--ef-border)", background: "var(--ef-bone-2)" }}>
                <UI.Stepper steps={window.TEMPLATE_SUB_STEPS} current={sub} />
              </div>
              <div style={{ padding: "22px 20px" }} key={sub}>
                <window.TemplateStepBody step={sub} t={t} showName={false} compact docType={d.category === "Manufacturing" ? "Purchase order" : d.category} onExtracted={() => setSub(1)} />
              </div>
            </div>
          </div>)}

          {step === 6 && (<div>
            <h2 style={{ fontSize: 30 }}>Test run</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 26 }}>Run the workflow once against a sample document to preview the result before activating.</p>
            <TestRunPanel input={d.input} output={d.output} toast={toast} />
          </div>)}

          {step === 7 && (<div>
            <h2 style={{ fontSize: 30 }}>When should this run?</h2>
            <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 26 }}>Choose how executions are triggered. You can change this anytime.</p>
            {[
              ["manual", "Manual only", "Run on demand from the project page.", "play"],
              ["file_uploaded", "Run on file upload", "Start a run whenever a file is uploaded.", "upload-cloud"],
              ["email_received", "Run when a matching email arrives", "Watch Gmail for matching messages.", "mail"],
              ["folder_updated", "Run when a folder receives a new file", "Monitor a Drive folder.", "hard-drive"],
              ["scheduled", "Run on a schedule", "Daily, weekly, or a custom cadence.", "clock"],
              ["api_request", "Run via API", "Trigger executions programmatically.", "webhook"],
            ].map(([id, t, s, ic]) => (
              <button key={id} onClick={() => set("activate", id)} className="card" style={{ width: "100%", textAlign: "left", padding: "14px 16px", marginBottom: 10, display: "flex", gap: 13, alignItems: "center", borderColor: d.activate === id ? "var(--ef-ink-950)" : "var(--ef-border)", background: d.activate === id ? "var(--ef-bone-2)" : "var(--ef-bg-raised)", cursor: "pointer" }}>
                <Icon name={ic} size={19} color="var(--ef-fg-3)" />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, color: "var(--ef-fg-1)", fontSize: 14 }}>{t}</div><div className="muted" style={{ fontSize: 12.5 }}>{s}</div></div>
                <div style={{ width: 20, height: 20, borderRadius: 999, border: d.activate === id ? 0 : "1.5px solid var(--ef-border-strong)", background: d.activate === id ? "var(--ef-ink-950)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>{d.activate === id && <Icon name="check" size={12} color="var(--ef-bone)" />}</div>
              </button>
            ))}
          </div>)}
        </div>
      </div>

      <div style={{ borderTop: "1px solid var(--ef-border)", padding: "14px 28px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <button className="link muted" style={{ fontSize: 13.5, fontWeight: 600, visibility: step === 0 ? "hidden" : "visible", display: "inline-flex", alignItems: "center", gap: 6 }} onClick={goBack}><Icon name="arrow-left" size={15} /> Back</button>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          {step === CONFIG_STEP && <span className="muted" style={{ fontSize: 12.5, fontWeight: 600 }}>Configuration step {sub + 1} of {window.TEMPLATE_SUB_STEPS.length}</span>}
          <UI.Button variant={last ? "accent" : "primary"} disabled={!canNext} iconRight="arrow-right" onClick={goNext}>
            {last ? "Create project" : "Continue"}
          </UI.Button>
        </div>
      </div>
    </div>
  );
}

function TestRunPanel({ input, output, toast }) {
  const [state, setState] = usePState("idle"); // idle | running | done
  const run = () => { setState("running"); setTimeout(() => setState("done"), 1900); };
  return (
    <div className="card" style={{ overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 18px", borderBottom: "1px solid var(--ef-border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11 }}><Icon name="file-text" size={18} color="var(--ef-fg-3)" /><span style={{ fontWeight: 700, color: "var(--ef-fg-1)", fontSize: 14 }} className="mono">zara_po_4417.pdf</span><span className="muted" style={{ fontSize: 12 }}>sample · 4 pages</span></div>
        <UI.Button variant={state === "done" ? "secondary" : "primary"} size="sm" icon={state === "running" ? undefined : "play"} disabled={state === "running"} onClick={run}>
          {state === "running" ? <><Icon name="loader" size={15} className="spin" /> Running…</> : state === "done" ? "Run again" : "Run test"}
        </UI.Button>
      </div>
      {state === "idle" && <div style={{ padding: "40px 18px", textAlign: "center" }} className="muted">Run the test to preview extracted data and the generated output.</div>}
      {state !== "idle" && (
        <div style={{ padding: 18 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Extracted fields</div>
              {DATA.sampleFields.filter((f) => f.selected).map((f) => (
                <div key={f.name} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid var(--ef-border)" }}>
                  <span style={{ fontSize: 13, color: "var(--ef-fg-3)" }}>{f.name}</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ef-fg-1)" }} className={state === "running" ? "pulse" : ""}>{state === "running" ? "···" : f.value}</span>
                </div>
              ))}
            </div>
            <div>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Generated output → {output}</div>
              <div className="card" style={{ background: "var(--ef-bone-2)", padding: 14, fontFamily: "var(--ef-font-mono)", fontSize: 12, lineHeight: 1.7, color: state === "running" ? "var(--ef-fg-4)" : "var(--ef-fg-1)" }}>
                {state === "running" ? "Generating…" : <>vendor_name,po_number,amount,delivery_date<br />Zara Sourcing Ltd.,PO-2026-04417,60140.00,2026-07-15</>}
              </div>
              {state === "done" && <div className="badge badge-solid" style={{ marginTop: 12, background: "#E7F2EA", color: "var(--ef-success)" }}><Icon name="check" size={12} color="var(--ef-success)" /> Test passed · 4 fields · 0 warnings</div>}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.FlowStrip = FlowStrip;
window.ProjectsList = ProjectsList;
window.CreateProjectWizard = CreateProjectWizard;
