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

const COMPLEXITY_COLOR = { Simple: "var(--ef-success)", Moderate: "var(--ef-warning)", Advanced: "var(--ef-coral)" };

function Marketplace({ navigate }) {
  const { CategoryChip, Button } = UI;
  const D = DATA;
  const [q, setQ] = useMState("");
  const [cat, setCat] = useMState("All");
  const cats = ["All", ...Array.from(new Set(D.marketplace.map((m) => m.category)))];
  let list = D.marketplace.filter((m) => (cat === "All" || m.category === cat) && (m.name.toLowerCase().includes(q.toLowerCase()) || m.desc.toLowerCase().includes(q.toLowerCase())));
  const featured = D.marketplace.filter((m) => m.featured);

  return (
    <div className="app-scroll"><div className="page fade-in">
      <UI.PageHeader eyebrow="Prebuilt by Docomate" title="Workflow marketplace" subtitle="Clone a ready-made workflow with mappings and recommended outputs, then customize it for your documents." />

      {cat === "All" && !q && (
        <div style={{ marginBottom: 30 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Featured</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
            {featured.map((m) => (
              <div key={m.id} className="card card-hover" style={{ padding: 0, overflow: "hidden" }} onClick={() => navigate("marketplaceDetail", { id: m.id })}>
                <div style={{ height: 88, background: "var(--ef-ink-950)", padding: 18, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                    <Icon name={iconFor(m)} size={22} color="var(--ef-beam-500)" />
                    <span className="badge badge-solid" style={{ background: "var(--ef-ink-800)", color: "var(--ef-bone)", fontSize: 10.5 }}>{m.clones.toLocaleString()} clones</span>
                  </div>
                  <div style={{ color: "var(--ef-bone)", fontWeight: 800, fontSize: 17, letterSpacing: "-0.02em" }}>{m.name}</div>
                </div>
                <div style={{ padding: 16 }}>
                  <p className="muted" style={{ fontSize: 13, lineHeight: 1.45, minHeight: 56, display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{m.desc}</p>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
                    <CategoryChip category={m.category} />
                    <span className="badge" style={{ color: COMPLEXITY_COLOR[m.complexity], borderColor: "transparent" }}><span className="dot" style={{ background: COMPLEXITY_COLOR[m.complexity], width: 6, height: 6 }} />{m.complexity}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 18, flexWrap: "wrap" }}>
        <div style={{ position: "relative", flex: 1, minWidth: 220, maxWidth: 340 }}>
          <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 workflows" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 36 }} />
        </div>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 22 }}>
        {cats.map((c) => <button key={c} className={`chip ${cat === c ? "selected" : ""}`} onClick={() => setCat(c)}>{c}</button>)}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 16 }}>
        {list.map((m) => (
          <div key={m.id} className="card" style={{ padding: 20, display: "flex", flexDirection: "column" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: "var(--ef-bone-2)", border: "1px solid var(--ef-border)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={iconFor(m)} size={20} color="var(--ef-fg-2)" /></div>
              <CategoryChip category={m.category} />
            </div>
            <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ef-fg-1)" }}>{m.name}</div>
            <p className="muted" style={{ fontSize: 13, marginTop: 6, lineHeight: 1.45, flex: 1, minHeight: 56, display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{m.desc}</p>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap", margin: "12px 0" }}>
              {m.inputs.slice(0, 3).map((s) => <span key={s} className="badge" style={{ fontSize: 10.5 }}>{s}</span>)}
            </div>
            <div className="divider" style={{ marginBottom: 12 }} />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div className="muted" style={{ fontSize: 11.5 }}><Icon name="clock" size={12} color="var(--ef-fg-4)" style={{ display: "inline", verticalAlign: "-2px" }} /> {m.time} setup · <span style={{ color: COMPLEXITY_COLOR[m.complexity], fontWeight: 700 }}>{m.complexity}</span></div>
              <UI.Button variant="secondary" size="sm" onClick={() => navigate("marketplaceDetail", { id: m.id })}>View</UI.Button>
            </div>
          </div>
        ))}
      </div>
    </div></div>
  );
}

function MarketplaceDetail({ navigate, toast, params }) {
  const { CategoryChip, Button } = UI;
  const D = DATA;
  const m = D.marketplace.find((x) => x.id === params?.id) || D.marketplace[0];
  const [cloneOpen, setCloneOpen] = useMState(false);

  const flow = [
    { type: "trigger", label: "Trigger" }, { type: "input", label: m.inputs[0] },
    { type: "processing", label: "Extract" }, { type: "processing", label: "Generate " + m.outputs[0] },
    ...(m.connectors.length ? [{ type: "output", label: m.connectors[0] }] : [{ type: "output", label: "Download" }]),
  ];

  return (
    <div className="app-scroll"><div className="page fade-in">
      <div style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr", gap: 32, alignItems: "start" }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
            <div style={{ width: 48, height: 48, borderRadius: 12, background: "var(--ef-ink-950)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={iconFor(m)} size={24} color="var(--ef-beam-500)" /></div>
            <div><CategoryChip category={m.category} /></div>
          </div>
          <h2 style={{ fontSize: 32 }}>{m.name}</h2>
          <p className="muted" style={{ fontSize: 16, marginTop: 12, lineHeight: 1.5 }}>{m.desc}</p>

          <div className="card card-pad" style={{ marginTop: 26 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Workflow preview</div>
            <FlowStrip steps={flow} />
          </div>

          <h5 style={{ fontSize: 17, marginTop: 30, marginBottom: 12 }}>Use case</h5>
          <p className="muted" style={{ fontSize: 14.5, lineHeight: 1.6 }}>{useCaseFor(m)}</p>

          <h5 style={{ fontSize: 17, marginTop: 30, marginBottom: 12 }}>Included steps</h5>
          <div className="card" style={{ overflow: "hidden" }}>
            {includedSteps(m).map((s, i) => (
              <div key={i} style={{ display: "flex", gap: 12, padding: "12px 16px", borderTop: i ? "1px solid var(--ef-border)" : 0, alignItems: "center" }}>
                <div style={{ width: 28, height: 28, borderRadius: 7, background: "var(--ef-bone-2)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={UI.NODE_TYPES[s.type].icon} size={15} color={UI.NODE_TYPES[s.type].color} /></div>
                <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ef-fg-1)", flex: 1 }}>{s.label}</span>
                <span className="badge" style={{ fontSize: 10.5 }}>{UI.NODE_TYPES[s.type].label}</span>
              </div>
            ))}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 30 }}>
            <div><h6 style={{ fontSize: 14, marginBottom: 10 }}>Sample input</h6><div className="card card-pad" style={{ display: "flex", gap: 10, alignItems: "center", background: "var(--ef-bone-2)" }}><Icon name="file-text" size={18} color="var(--ef-fg-3)" /><span className="mono" style={{ fontSize: 12.5, color: "var(--ef-fg-1)" }}>sample_{m.category.toLowerCase()}.pdf</span></div></div>
            <div><h6 style={{ fontSize: 14, marginBottom: 10 }}>Sample output</h6><div className="card card-pad" style={{ display: "flex", gap: 10, alignItems: "center", background: "var(--ef-bone-2)" }}><Icon name="file-spreadsheet" size={18} color="var(--ef-fg-3)" /><span className="mono" style={{ fontSize: 12.5, color: "var(--ef-fg-1)" }}>output.{(m.outputs[0] || "csv").toLowerCase().slice(0, 4)}</span></div></div>
          </div>
        </div>

        <div style={{ position: "sticky", top: 0, display: "flex", flexDirection: "column", gap: 18 }}>
          <div className="card card-pad">
            <Button variant="accent" icon="copy" style={{ width: "100%" }} onClick={() => setCloneOpen(true)}>Clone workflow</Button>
            <div style={{ marginTop: 16, fontSize: 13, lineHeight: 2 }}>
              <Row k="Complexity" v={<span style={{ color: COMPLEXITY_COLOR[m.complexity], fontWeight: 700 }}>{m.complexity}</span>} />
              <Row k="Setup required" v={m.setup} /><Row k="Estimated setup" v={m.time} /><Row k="Cloned" v={m.clones.toLocaleString() + " times"} /><Row k="Version" v="1.2" /><Row k="Publisher" v="Docomate" />
            </div>
          </div>
          <div className="card card-pad">
            <div className="eyebrow" style={{ marginBottom: 12 }}>Inputs</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 16 }}>{m.inputs.map((i) => <span key={i} className="badge">{i}</span>)}</div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Outputs</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: m.connectors.length ? 16 : 0 }}>{m.outputs.map((i) => <span key={i} className="badge">{i}</span>)}</div>
            {m.connectors.length > 0 && <><div className="eyebrow" style={{ marginBottom: 12 }}>Required connectors</div><div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>{m.connectors.map((c) => <span key={c} className="badge"><Icon name="link" size={11} color="var(--ef-fg-4)" />{c}</span>)}</div></>}
          </div>
        </div>
      </div>

      {cloneOpen && <CloneModal m={m} onClose={() => setCloneOpen(false)} navigate={navigate} toast={toast} />}
    </div></div>
  );
}

function CloneModal({ m, onClose, navigate, toast }) {
  const [mode, setMode] = useMState("new");
  const [proj, setProj] = useMState(DATA.projects[0].id);
  const [name, setName] = useMState(m.name);
  return (
    <UI.Modal title="Clone workflow" subtitle={`Copy "${m.name}" into a project as a draft.`} onClose={onClose}
      footer={<>
        <UI.Button variant="ghost" onClick={onClose}>Cancel</UI.Button>
        <UI.Button variant="primary" icon="copy" onClick={() => { onClose(); toast("Workflow cloned · opening builder", "success"); navigate(mode === "new" ? "builder" : "builder", { id: "proj_po" }); }}>Clone & open builder</UI.Button>
      </>}>
      <div className="seg" style={{ marginBottom: 18, width: "100%" }}>
        <button className={mode === "new" ? "active" : ""} onClick={() => setMode("new")} style={{ flex: 1 }}>New project</button>
        <button className={mode === "existing" ? "active" : ""} onClick={() => setMode("existing")} style={{ flex: 1 }}>Existing project</button>
      </div>
      {mode === "new" ? <UI.Field label="Project name"><input className="input" value={name} onChange={(e) => setName(e.target.value)} /></UI.Field>
        : <UI.Field label="Choose project"><select className="select" value={proj} onChange={(e) => setProj(e.target.value)}>{DATA.projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></UI.Field>}
      <div className="card card-pad" style={{ background: "var(--ef-bone-2)", marginTop: 4 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ef-fg-1)", marginBottom: 8 }}>After cloning you'll</div>
        {["Connect any required connectors", "Complete template setup if needed", "Test, then activate"].map((s, i) => (
          <div key={i} style={{ display: "flex", gap: 9, alignItems: "center", padding: "3px 0", fontSize: 13, color: "var(--ef-fg-2)" }}><Icon name="check" size={14} color="var(--ef-success)" />{s}</div>
        ))}
      </div>
    </UI.Modal>
  );
}

function Row({ 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>; }
function iconFor(m) { return ({ "Invoice to Excel": "file-spreadsheet", "Purchase order to CSV": "package", "Contract summary": "file-text", "PDF page splitter": "scissors", "Translate contract to English": "languages", "Bank statement analyzer": "calculator", "Insurance claim extraction": "shield", "Resume parser": "user", "Multi-document consolidation": "git-merge", "Duplicate invoice detection": "copy", "Report to presentation": "presentation", "Lab report structuring": "table" })[m.name] || "git-branch"; }
function useCaseFor(m) {
  return ({
    mkt_po_csv: "A garments manufacturer receives many purchase orders from the same buyer in the same layout. Instead of a person reading each one and typing selected fields into another system, this workflow extracts them and produces an ERP-ready CSV automatically.",
    mkt_inv_excel: "Finance teams receive supplier invoices as PDFs by email. This workflow reads each invoice, extracts header fields and line-item tables, and consolidates them into a clean Excel spreadsheet.",
  })[m.id] || `Teams in ${m.category.toLowerCase()} receive these documents repeatedly. Configure the template once, and every future document is processed and delivered the same way without manual work.`;
}
function includedSteps(m) {
  return [
    { type: "trigger", label: "File uploaded or fetched" }, { type: "input", label: `Receive from ${m.inputs[0]}` },
    { type: "processing", label: "OCR & extract fields" }, { type: "processing", label: m.setup === "Field mapping" ? "Map fields to template" : "Select configured fields" },
    { type: "processing", label: `Generate ${m.outputs[0]}` }, { type: "output", label: m.connectors[0] ? `Deliver to ${m.connectors[0]}` : "Downloadable artifact" },
  ];
}

window.Marketplace = Marketplace;
window.MarketplaceDetail = MarketplaceDetail;
