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

const COLS = ["A", "B", "C", "D", "E", "F", "G", "H"];
const TEMPLATE_SUB_STEPS = ["Sample", "Extract", "Select", "Format", "Map", "Save"];

// ---- shared state for the template configuration steps ----
function useTemplateData(initialName) {
  const [fields, setFields] = useTState(() => DATA.sampleFields.map((f, i) => ({ ...f, id: "f" + i, column: f.selected ? COLS[["Vendor name", "PO number", "Amount", "Delivery date"].indexOf(f.name)] || "" : "" })));
  const [extracted, setExtracted] = useTState(false);
  const [format, setFormat] = useTState("CSV");
  const [meta, setMeta] = useTState({ name: initialName || "New template", threshold: 85, onMissing: "review" });
  const selected = fields.filter((f) => f.selected);
  return {
    fields, setFields, extracted, setExtracted, format, setFormat, meta, setMeta, selected,
    toggleField: (id) => setFields((fs) => fs.map((f) => f.id === id ? { ...f, selected: !f.selected } : f)),
    setCol: (id, col) => setFields((fs) => fs.map((f) => f.id === id ? { ...f, column: col } : f)),
  };
}

// canNext for template sub-steps 0–5
function templateCanNext(step, t, requireName) {
  return [t.extracted, true, t.selected.length > 0, !!t.format, true, requireName ? t.meta.name.trim().length > 1 : true][step];
}

// ---- the 6 configuration step bodies, shared by both hosts ----
function TemplateStepBody({ step, t, showName = true, docType, onExtracted, compact }) {
  const { fields, format, setFormat, meta, setMeta, selected, toggleField, setCol, setFields } = t;
  const H = compact
    ? ({ children }) => <h4 style={{ fontSize: 20 }}>{children}</h4>
    : ({ children }) => <h2 style={{ fontSize: 28 }}>{children}</h2>;

  if (step === 0) return <StepSample compact={compact} onExtract={() => { t.setExtracted(true); onExtracted?.(); }} />;

  if (step === 1) return (
    <div>
      <H>Review extracted fields</H>
      <p className="muted" style={{ fontSize: compact ? 13.5 : 14.5, marginTop: 8, marginBottom: 20 }}>Docomate found {fields.length} fields. Rename, merge, or ignore any field. Confidence is shown for each.</p>
      <div style={{ display: "grid", gridTemplateColumns: "0.9fr 1.1fr", gap: 20, alignItems: "start" }}>
        <DocPreview />
        <div className="card" style={{ overflow: "hidden" }}>
          <table className="tbl">
            <thead><tr><th>Field</th><th>Value</th><th>Type</th><th style={{ textAlign: "right" }}>Conf.</th></tr></thead>
            <tbody>{fields.map((f) => (
              <tr key={f.id}>
                <td style={{ fontWeight: 600, color: "var(--ef-fg-1)" }}>{f.name}</td>
                <td className="muted" style={{ maxWidth: 130, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{f.value}</td>
                <td><span className="badge" style={{ fontSize: 10.5 }}>{f.type}</span></td>
                <td style={{ textAlign: "right" }}><ConfPill v={f.conf} /></td>
              </tr>))}</tbody>
          </table>
        </div>
      </div>
    </div>
  );

  if (step === 2) return (
    <div>
      <H>Select the fields you need</H>
      <p className="muted" style={{ fontSize: compact ? 13.5 : 14.5, marginTop: 8, marginBottom: 16 }}>Choose which fields to keep. Your selection is saved and reused for every future document.</p>
      <div style={{ display: "flex", gap: 10, marginBottom: 14, alignItems: "center" }}>
        <UI.Button variant="secondary" size="sm" icon="list-checks" onClick={() => setFields((fs) => fs.map((f) => ({ ...f, selected: f.conf >= 0.9 })))}>Select all high-confidence</UI.Button>
        <UI.Button variant="ghost" size="sm" onClick={() => setFields((fs) => fs.map((f) => ({ ...f, selected: false })))}>Clear</UI.Button>
        <div style={{ flex: 1 }} />
        <span className="badge">{selected.length} selected</span>
      </div>
      <div className="card" style={{ overflow: "hidden" }}>
        {fields.map((f, i) => (
          <div key={f.id} onClick={() => toggleField(f.id)} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 16px", borderTop: i ? "1px solid var(--ef-border)" : 0, cursor: "pointer", background: f.selected ? "var(--ef-bone-2)" : "transparent" }}>
            <div style={{ width: 20, height: 20, borderRadius: 5, border: f.selected ? 0 : "1.5px solid var(--ef-border-strong)", background: f.selected ? "var(--ef-ink-950)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{f.selected && <Icon name="check" size={13} color="var(--ef-bone)" />}</div>
            <div style={{ flex: 1, minWidth: 0 }}><span style={{ fontSize: 14, fontWeight: 600, color: "var(--ef-fg-1)" }}>{f.name}</span><span className="muted" style={{ fontSize: 12.5, marginLeft: 10 }}>{f.value}</span></div>
            <span className="badge" style={{ fontSize: 10.5 }}>{f.type}</span>
            <span className="badge" style={{ fontSize: 10.5 }}>p{f.page}</span>
            <ConfPill v={f.conf} />
          </div>
        ))}
      </div>
    </div>
  );

  if (step === 3) return (
    <div>
      <H>Choose the output format</H>
      <p className="muted" style={{ fontSize: compact ? 13.5 : 14.5, marginTop: 8, marginBottom: 8 }}>This generates the file. Where it's delivered is configured as an output node in the workflow.</p>
      <div className="badge" style={{ marginBottom: 20, background: "var(--ef-beam-100)", color: "var(--ef-beam-700)", border: 0 }}><Icon name="info" size={13} color="var(--ef-beam-700)" /> Generating a file is processing — delivery is output</div>
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${compact ? 4 : 4}, 1fr)`, gap: 12 }}>
        {[["CSV", "file-spreadsheet"], ["Excel", "file-spreadsheet"], ["JSON", "file-json"], ["DOCX", "file-text"], ["PDF", "file-text"], ["PPTX", "presentation"], ["On-screen report", "bar-chart"]].map(([f, ic]) => (
          <button key={f} onClick={() => setFormat(f)} className="card" style={{ padding: 16, display: "flex", flexDirection: "column", alignItems: "center", gap: 9, cursor: "pointer", borderColor: format === f ? "var(--ef-ink-950)" : "var(--ef-border)", background: format === f ? "var(--ef-bone-2)" : "var(--ef-bg-raised)" }}>
            <Icon name={ic} size={22} color={format === f ? "var(--ef-ink-950)" : "var(--ef-fg-3)"} /><span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ef-fg-1)", textAlign: "center" }}>{f}</span>
          </button>
        ))}
      </div>
    </div>
  );

  if (step === 4) return (
    <div>
      <H>Map fields to {format} columns</H>
      <p className="muted" style={{ fontSize: compact ? 13.5 : 14.5, marginTop: 8, marginBottom: 20 }}>Assign each selected field to a column. This mapping becomes the fixed output structure for future runs.</p>
      <div style={{ display: "grid", gridTemplateColumns: "0.9fr 1.1fr", gap: 20, alignItems: "start" }}>
        <div className="card" style={{ overflow: "hidden" }}>
          <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--ef-border)", fontWeight: 700, fontSize: 13.5, color: "var(--ef-fg-1)" }}>Selected fields</div>
          {selected.map((f, i) => (
            <div key={f.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 16px", borderTop: i ? "1px solid var(--ef-border)" : 0 }}>
              <Icon name="grip-vertical" size={15} color="var(--ef-fg-4)" />
              <span style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: "var(--ef-fg-1)" }}>{f.name}</span>
              <span className="muted" style={{ fontSize: 12 }}>→</span>
              <select className="select" value={f.column} onChange={(e) => setCol(f.id, e.target.value)} style={{ width: 92, height: 34, padding: "0 26px 0 10px" }}>
                <option value="">—</option>{COLS.map((c) => <option key={c} value={c}>Col {c}</option>)}
              </select>
            </div>
          ))}
        </div>
        <div>
          <div className="eyebrow" style={{ marginBottom: 10 }}>{format} preview</div>
          <div className="card" style={{ overflow: "auto" }}>
            <table className="tbl" style={{ fontSize: 12.5 }}>
              <thead><tr>{COLS.slice(0, Math.max(4, selected.length)).map((c) => { const f = selected.find((x) => x.column === c); return <th key={c} className="mono">{c}{f ? ` · ${f.name}` : ""}</th>; })}</tr></thead>
              <tbody><tr>{COLS.slice(0, Math.max(4, selected.length)).map((c) => { const f = selected.find((x) => x.column === c); return <td key={c} className="mono" style={{ color: f ? "var(--ef-fg-1)" : "var(--ef-fg-4)" }}>{f ? f.value : "—"}</td>; })}</tr></tbody>
            </table>
          </div>
          <p className="muted" style={{ fontSize: 12.5, marginTop: 12, lineHeight: 1.5 }}>For PDF-to-PDF transforms, you'd map source fields onto a destination template layout instead of columns.</p>
        </div>
      </div>
    </div>
  );

  if (step === 5) return (
    <div>
      <H>{showName ? "Save the template" : "Save the configuration"}</H>
      <p className="muted" style={{ fontSize: compact ? 13.5 : 14.5, marginTop: 8, marginBottom: 20 }}>Set how Docomate should behave when a document doesn't match perfectly.</p>
      <div style={{ maxWidth: 520 }}>
        {showName && <UI.Field label="Template name" required><input className="input" value={meta.name} onChange={(e) => setMeta((m) => ({ ...m, name: e.target.value }))} /></UI.Field>}
        <UI.Field label={`Match confidence threshold — ${meta.threshold}%`} help="Below this, a document is routed to human review instead of auto-processing.">
          <input type="range" min="50" max="99" value={meta.threshold} onChange={(e) => setMeta((m) => ({ ...m, threshold: +e.target.value }))} style={{ width: "100%", accentColor: "var(--ef-ink-950)" }} />
        </UI.Field>
        <UI.Field label="When a required field is missing">
          <select className="select" value={meta.onMissing} onChange={(e) => setMeta((m) => ({ ...m, onMissing: e.target.value }))}>
            <option value="review">Send to human review</option><option value="warn">Continue with a warning</option><option value="fail">Fail the execution</option>
          </select>
        </UI.Field>
        <div className="card card-pad" style={{ background: "var(--ef-bone-2)", marginTop: 6 }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Summary</div>
          <div style={{ fontSize: 13, lineHeight: 1.9, color: "var(--ef-fg-2)" }}>
            <Line k="Document type" v={docType || "Document"} />
            <Line k="Fields selected" v={selected.length} /><Line k="Output format" v={format} /><Line k="Mapped columns" v={selected.filter((f) => f.column).length} />
          </div>
        </div>
      </div>
    </div>
  );
  return null;
}

// ============================ standalone template wizard ============================
function TemplateWizard({ navigate, toast, params }) {
  const projId = params?.project || params?.id;
  const proj = DATA.projects.find((p) => p.id === projId);
  const backTo = projId && projId !== "new" ? () => navigate("project", { id: projId }) : () => navigate("projects");

  const [step, setStep] = useTState(0);
  const t = useTemplateData((params?.name || proj?.name || "New") + " template");
  const [testState, setTestState] = useTState("idle");

  const steps = [...TEMPLATE_SUB_STEPS, "Test", "Activate"];
  const last = step === steps.length - 1;
  const canNext = step <= 5 ? templateCanNext(step, t, true) : true;
  const docType = proj?.category === "Manufacturing" ? "Purchase order" : "Document";

  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, flexShrink: 0 }}>
          <button className="btn btn-ghost btn-sm" onClick={backTo}><Icon name="x" size={16} /></button>
          <div style={{ display: "flex", flexDirection: "column", maxWidth: 200 }}>
            <span style={{ fontWeight: 800, fontSize: 15, whiteSpace: "nowrap" }}>Template setup</span>
            <span className="muted" style={{ fontSize: 11.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Configure once · reuse every run</span>
          </div>
        </div>
        <div style={{ flex: 1, maxWidth: 720, margin: "0 28px" }}><UI.Stepper steps={steps} current={step} /></div>
        <div style={{ width: 60 }} />
      </div>

      <div style={{ flex: 1, overflowY: "auto" }}>
        <div style={{ maxWidth: step === 1 || step === 4 || step === 6 ? 1080 : 760, margin: "0 auto", padding: "32px 24px 60px" }} className="fade-in" key={step}>
          {step <= 5 && <TemplateStepBody step={step} t={t} showName docType={docType} onExtracted={() => setStep(1)} />}
          {step === 6 && <StepTest state={testState} setState={setTestState} fields={t.selected} format={t.format} threshold={t.meta.threshold} />}
          {step === 7 && (
            <div style={{ textAlign: "center", maxWidth: 520, margin: "0 auto", paddingTop: 20 }}>
              <div style={{ width: 64, height: 64, borderRadius: 16, background: "var(--ef-beam-500)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 20px" }}><Icon name="check" size={32} color="var(--ef-ink-950)" /></div>
              <h2 style={{ fontSize: 28 }}>Template ready to activate</h2>
              <p className="muted" style={{ fontSize: 15, marginTop: 12, lineHeight: 1.5 }}>Once active, every matching document reuses this field selection, mapping, and output format automatically — no setup needed per run.</p>
              <div className="card card-pad" style={{ textAlign: "left", marginTop: 24 }}>
                <Line k="Template" v={t.meta.name} /><Line k="Version" v="1" /><Line k="Fields" v={`${t.selected.length} selected`} /><Line k="Output" v={t.format} /><Line k="Match threshold" v={t.meta.threshold + "%"} />
              </div>
            </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={() => setStep((s) => s - 1)}><Icon name="arrow-left" size={15} /> Back</button>
        {step !== 0 && <UI.Button variant={last ? "accent" : "primary"} disabled={!canNext} iconRight={last ? "check" : "arrow-right"}
          onClick={() => { if (last) { toast("Template activated", "success"); backTo(); } else setStep((s) => s + 1); }}>{last ? "Activate template" : "Continue"}</UI.Button>}
      </div>
    </div>
  );
}

function StepSample({ onExtract, compact }) {
  const [file, setFile] = useTState(false);
  const [running, setRunning] = useTState(false);
  return (
    <div>
      {compact ? <h4 style={{ fontSize: 20 }}>Upload a sample document</h4> : <h2 style={{ fontSize: 28 }}>Upload a sample document</h2>}
      <p className="muted" style={{ fontSize: compact ? 13.5 : 14.5, marginTop: 8, marginBottom: 22 }}>Docomate learns the layout from one example. Future documents of the same type reuse what you configure here.</p>
      {!file ? (
        <button onClick={() => setFile(true)} style={{ width: "100%", border: "1.5px dashed var(--ef-border-strong)", borderRadius: 14, background: "var(--ef-bone-2)", padding: compact ? "40px 24px" : "56px 24px", display: "flex", flexDirection: "column", alignItems: "center", gap: 12, cursor: "pointer" }}>
          <div style={{ width: 56, height: 56, borderRadius: 14, background: "var(--ef-bg-raised)", border: "1px solid var(--ef-border)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="upload-cloud" size={26} color="var(--ef-fg-3)" /></div>
          <div style={{ fontSize: 15, fontWeight: 700, color: "var(--ef-fg-1)" }}>Drop a sample document, or click to choose</div>
          <div className="muted" style={{ fontSize: 13 }}>PDF, DOCX, XLSX, JPG, PNG, or TIFF · up to 50 MB</div>
        </button>
      ) : (
        <div className="card card-pad">
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: "var(--ef-bone-2)", border: "1px solid var(--ef-border)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="file-text" size={22} color="var(--ef-fg-3)" /></div>
            <div style={{ flex: 1 }}><div className="mono" style={{ fontWeight: 700, color: "var(--ef-fg-1)", fontSize: 14 }}>zara_po_4417.pdf</div><div className="muted" style={{ fontSize: 12.5 }}>1.4 MB · 4 pages</div></div>
            <button className="btn btn-ghost btn-icon btn-sm" onClick={() => setFile(false)}><Icon name="x" size={16} /></button>
          </div>
          <div style={{ display: "flex", gap: 8, marginBottom: 18 }}>{[1, 2, 3, 4].map((p) => <div key={p} style={{ width: 56, height: 72, borderRadius: 6, background: "var(--ef-bg-raised)", border: "1px solid var(--ef-border-strong)", display: "flex", alignItems: "flex-end", padding: 5, position: "relative" }}><div style={{ position: "absolute", top: 6, left: 6, right: 6, height: 3, background: "var(--ef-ink-100)" }} /><span className="mono muted" style={{ fontSize: 9 }}>p{p}</span></div>)}</div>
          <UI.Button variant="primary" disabled={running} onClick={() => { setRunning(true); setTimeout(onExtract, 1400); }}>
            {running ? <><Icon name="loader" size={16} className="spin" /> Extracting fields…</> : <><Icon name="sparkles" size={16} /> Run extraction</>}
          </UI.Button>
        </div>
      )}
    </div>
  );
}

function DocPreview() {
  const boxes = [["Vendor name", 18, 92], ["PO number", 56, 92], ["Delivery date", 18, 70], ["Amount", 56, 40]];
  return (
    <div className="card" style={{ padding: 16, background: "var(--ef-bone-2)", position: "sticky", top: 0 }}>
      <div className="eyebrow" style={{ marginBottom: 10 }}>Sample · page 1</div>
      <div style={{ position: "relative", background: "var(--ef-bg-raised)", border: "1px solid var(--ef-border-strong)", borderRadius: 6, aspectRatio: "3/4", padding: 18 }}>
        <div style={{ height: 10, width: "55%", background: "var(--ef-ink-200)", borderRadius: 3, marginBottom: 16 }} />
        {[80, 95, 70, 88, 60].map((w, i) => <div key={i} style={{ height: 6, width: w + "%", background: "var(--ef-ink-100)", borderRadius: 3, marginBottom: 9 }} />)}
        <div style={{ height: 40 }} />
        {[92, 78, 85].map((w, i) => <div key={i} style={{ height: 6, width: w + "%", background: "var(--ef-ink-100)", borderRadius: 3, marginBottom: 9 }} />)}
        {boxes.map(([label, l, t], i) => (
          <div key={i} style={{ position: "absolute", left: l + "%", top: (100 - t) + "%", border: "1.5px solid var(--ef-beam-500)", background: "rgba(245,165,36,0.12)", borderRadius: 4, padding: "2px 6px", fontSize: 9, fontWeight: 700, color: "var(--ef-beam-700)" }}>{label}</div>
        ))}
      </div>
    </div>
  );
}

function StepTest({ state, setState, fields, format, threshold }) {
  const run = () => { setState("running"); setTimeout(() => setState("done"), 1700); };
  return (
    <div>
      <h2 style={{ fontSize: 28 }}>Test the template</h2>
      <p className="muted" style={{ fontSize: 14.5, marginTop: 8, marginBottom: 22 }}>Upload a second sample to confirm the template matches and produces the right output.</p>
      <div className="card" style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 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 className="mono" style={{ fontWeight: 700, color: "var(--ef-fg-1)", fontSize: 13.5 }}>zara_po_4418.pdf</span><span className="muted" style={{ fontSize: 12 }}>second sample</span></div>
          <UI.Button variant="primary" size="sm" disabled={state === "running"} onClick={run}>{state === "running" ? <><Icon name="loader" size={15} className="spin" /> Matching…</> : state === "done" ? "Run again" : <><Icon name="play" size={15} /> Run test</>}</UI.Button>
        </div>
        {state === "idle" ? <div style={{ padding: "44px", textAlign: "center" }} className="muted">Run the test to see the match result and generated output.</div> : (
          <div style={{ padding: 18 }}>
            <div className="badge badge-solid" style={{ background: state === "running" ? "var(--ef-bone-3)" : "#E7F2EA", color: state === "running" ? "var(--ef-fg-3)" : "var(--ef-success)", marginBottom: 16 }}>
              <Icon name={state === "running" ? "loader" : "check-circle"} size={13} className={state === "running" ? "spin" : ""} color={state === "running" ? "var(--ef-fg-3)" : "var(--ef-success)"} />
              {state === "running" ? "Comparing to template…" : `Template matched · 96% confidence (threshold ${threshold}%)`}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
              <div><div className="eyebrow" style={{ marginBottom: 10 }}>Extracted & mapped</div>
                {fields.map((f) => <div key={f.id} style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: "1px solid var(--ef-border)" }}><span style={{ fontSize: 13, color: "var(--ef-fg-3)" }}>{f.name}{f.column && <span className="mono muted" style={{ fontSize: 11 }}> · {f.column}</span>}</span><span style={{ fontSize: 13, fontWeight: 600, color: "var(--ef-fg-1)" }}>{state === "running" ? "···" : f.value}</span></div>)}
              </div>
              <div><div className="eyebrow" style={{ marginBottom: 10 }}>Generated {format}</div>
                <div className="card mono" style={{ background: "var(--ef-bone-2)", padding: 14, fontSize: 11.5, lineHeight: 1.7, color: state === "running" ? "var(--ef-fg-4)" : "var(--ef-fg-1)" }}>{state === "running" ? "Generating…" : <>{fields.filter((f) => f.column).map((f) => f.name.toLowerCase().replace(/ /g, "_")).join(",")}<br />{fields.filter((f) => f.column).map((f) => f.value).join(",")}</>}</div>
                {state === "done" && <div className="muted" style={{ fontSize: 12, marginTop: 10 }}>No differences from the first sample · 0 warnings</div>}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function ConfPill({ v }) {
  const c = v >= 0.9 ? "var(--ef-success)" : v >= 0.75 ? "var(--ef-warning)" : "var(--ef-danger)";
  return <span className="mono" style={{ fontSize: 11.5, fontWeight: 700, color: c }}>{Math.round(v * 100)}%</span>;
}
function Line({ k, v }) { return <div style={{ display: "flex", justifyContent: "space-between" }}><span className="muted">{k}</span><span style={{ color: "var(--ef-fg-1)", fontWeight: 600 }}>{v}</span></div>; }

Object.assign(window, { TemplateWizard, TemplateStepBody, useTemplateData, templateCanNext, TEMPLATE_SUB_STEPS });
