/* Sentosa Marketplace - Seller Portal screens */

function statusTone(s) {
  return { Live: "success", "Low stock": "warning", "Sold out": "danger", Draft: "neutral",
    Confirmed: "success", Processing: "info", Refunded: "neutral" }[s] || "neutral";
}

function KpiCard({ label, value, delta, up, icon }) {
  return (
    <Card pad={18}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{ fontSize: 13, color: "var(--fg2)", fontWeight: 500 }}>{label}</div>
        <div style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", background: "var(--orange-50)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={icon} size={18} color="var(--orange-900)" /></div>
      </div>
      <div style={{ fontSize: 26, fontWeight: 700, margin: "10px 0 4px" }}>{value}</div>
      {delta && <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 13, color: up ? "var(--success)" : "var(--danger)", fontWeight: 600 }}>
        <Icon name={up ? "trending-up" : "trending-down"} size={15} />{delta}<span style={{ color: "var(--fg3)", fontWeight: 400 }}>vs last week</span>
      </div>}
    </Card>
  );
}

function DashboardScreen({ onNav }) {
  const maxBar = Math.max(...window.SALES_BARS.map(b => b[1]));
  return (
    <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 24 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 18 }}>
        <KpiCard label="Sales (7 days)" value="S$48,210" delta="+12.4%" up icon="dollar-sign" />
        <KpiCard label="Orders" value="318" delta="+8.1%" up icon="receipt-text" />
        <KpiCard label="Conversion" value="4.6%" delta="−0.3%" up={false} icon="target" />
        <KpiCard label="Active products" value="14" icon="package" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
        {/* Sales chart */}
        <Card pad={20}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
            <div><div style={{ fontWeight: 600, fontSize: 16 }}>Daily sales</div><div className="caption">This week · Singapore Dollars</div></div>
            <Badge tone="brand" dot={false}>Trade volume</Badge>
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 14, height: 180, paddingTop: 8 }}>
            {window.SALES_BARS.map(([day, v]) => (
              <div key={day} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, height: "100%", justifyContent: "flex-end" }}>
                <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--fg2)" }}>{v}</div>
                <div style={{ width: "100%", maxWidth: 38, height: `${(v / maxBar) * 100}%`, background: v === maxBar ? "var(--action)" : "var(--orange-700)", borderRadius: "var(--radius-sm) var(--radius-sm) 0 0", transition: "height .3s" }}></div>
                <div style={{ fontSize: 12, color: "var(--fg2)" }}>{day}</div>
              </div>
            ))}
          </div>
        </Card>

        {/* Inventory alerts */}
        <Card pad={20}>
          <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 16 }}>Needs attention</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {[["Cable Car Night Pass", "Sold out - restock", "danger", "alert-octagon"],
              ["Sky Dining Experience", "Low stock - 64 left", "warning", "alert-triangle"],
              ["Festive Season Pass", "Draft - not published", "neutral", "file-clock"]].map(([n, m, tone, ic]) => (
              <div key={n} style={{ display: "flex", gap: 12, alignItems: "center", padding: "10px 12px", border: "1px solid var(--border)", borderRadius: "var(--radius-md)" }}>
                <Icon name={ic} size={19} color={tone === "danger" ? "var(--danger)" : tone === "warning" ? "var(--warning)" : "var(--fg3)"} />
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 14, fontWeight: 600 }}>{n}</div><div style={{ fontSize: 12.5, color: "var(--fg2)" }}>{m}</div></div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Recent orders */}
      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontWeight: 600, fontSize: 16 }}>Recent orders</div>
          <Btn size="sm" variant="ghost" iconRight="arrow-right" onClick={() => onNav && onNav("orders")}>View all</Btn>
        </div>
        <OrdersTable rows={window.RECENT_ORDERS} />
      </Card>
    </div>
  );
}

function OrdersTable({ rows }) {
  const th = { textAlign: "left", padding: "11px 20px", fontSize: 12, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--fg2)", borderBottom: "1px solid var(--border)" };
  const td = { padding: "13px 20px", fontSize: 14.5, borderBottom: "1px solid var(--border)" };
  return (
    <div style={{ overflowX: "auto" }}>
    <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 640 }}>
      <thead><tr><th style={th}>Order</th><th style={th}>Buyer</th><th style={th}>Items</th><th style={{ ...th, textAlign: "right" }}>Total</th><th style={th}>Status</th><th style={{ ...th, textAlign: "right" }}>Date</th></tr></thead>
      <tbody>
        {rows.map((o, i) => (
          <tr key={o.ref}>
            <td style={{ ...td, fontFamily: "var(--font-mono)", fontWeight: 600 }}>{o.ref}</td>
            <td style={td}>{o.buyer}</td>
            <td style={td}>{o.items}</td>
            <td style={{ ...td, textAlign: "right", fontWeight: 600 }}>S${o.total.toFixed(2)}</td>
            <td style={td}><Badge tone={statusTone(o.status)}>{o.status}</Badge></td>
            <td style={{ ...td, textAlign: "right", color: "var(--fg2)" }}>{o.date}</td>
          </tr>
        ))}
      </tbody>
    </table>
    </div>
  );
}

function ProductsScreen({ onEdit }) {
  const [q, setQ] = React.useState("");
  const [status, setStatus] = React.useState("All");
  const rows = window.SELLER_PRODUCTS.filter(p =>
    (status === "All" || p.status === status) &&
    (p.name + p.id).toLowerCase().includes(q.toLowerCase()));
  const th = { textAlign: "left", padding: "11px 20px", fontSize: 12, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--fg2)", borderBottom: "1px solid var(--border)" };
  const td = { padding: "13px 20px", fontSize: 14.5, borderBottom: "1px solid var(--border)" };
  return (
    <div style={{ padding: 32 }}>
      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", gap: 12, alignItems: "center" }}>
          <div style={{ position: "relative", flex: 1, maxWidth: 320 }}>
            <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", display: "flex" }}><Icon name="search" size={17} color="var(--fg3)" /></span>
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search products or SKU"
              style={{ width: "100%", boxSizing: "border-box", height: 40, padding: "0 12px 0 36px", borderRadius: "var(--radius-md)", border: "1.5px solid var(--border)", fontSize: 14, fontFamily: "var(--font-sans)", outline: "none" }} />
          </div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {["All", "Live", "Low stock", "Sold out", "Draft", "In review"].map(s => (
              <button key={s} onClick={() => setStatus(s)}
                style={{ padding: "7px 12px", borderRadius: "var(--radius-pill)", cursor: "pointer", fontFamily: "var(--font-sans)",
                  fontSize: 12.5, fontWeight: status === s ? 600 : 500,
                  border: "1px solid " + (status === s ? "var(--black)" : "var(--border)"),
                  background: status === s ? "var(--black)" : "#fff", color: status === s ? "#fff" : "var(--fg2)" }}>{s}</button>
            ))}
          </div>
          <div style={{ marginLeft: "auto" }}>
            <ExportButtons name="Product master report" rows={rows.length} />
          </div>
        </div>
        <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 760 }}>
          <thead><tr><th style={th}>Product</th><th style={th}>SKU</th><th style={th}>Type</th><th style={{ ...th, textAlign: "right" }}>Trade price</th><th style={{ ...th, textAlign: "right" }}>Stock</th><th style={{ ...th, textAlign: "right" }}>7-day sales</th><th style={th}>Status</th><th style={th}></th></tr></thead>
          <tbody>
            {rows.map(p => (
              <tr key={p.id}>
                <td style={{ ...td, fontWeight: 600 }}>{p.name}</td>
                <td style={{ ...td, fontFamily: "var(--font-mono)", color: "var(--fg2)", fontSize: 13 }}>{p.id}</td>
                <td style={td}><span style={{ color: "var(--fg2)" }}>{p.type}</span></td>
                <td style={{ ...td, textAlign: "right" }}>S${p.trade.toFixed(2)}</td>
                <td style={{ ...td, textAlign: "right", color: p.stock === 0 ? "var(--danger)" : p.stock < 100 ? "var(--warning)" : "var(--fg1)", fontWeight: p.stock < 100 ? 600 : 400 }}>{p.stock.toLocaleString()}</td>
                <td style={{ ...td, textAlign: "right" }}>{p.sales7}</td>
                <td style={td}><Badge tone={statusTone(p.status)}>{p.status}</Badge></td>
                <td style={{ ...td, textAlign: "right" }}><button onClick={() => onEdit(p)} aria-label={`Edit ${p.name}`} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--orange-link)", fontWeight: 600, fontFamily: "var(--font-sans)", fontSize: 14, display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="pencil" size={15} />Edit</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>
    </div>
  );
}

function ProductEditor({ product, onBack }) {
  const p = product || {};
  const [submitted, setSubmitted] = React.useState(false);
  const [f, setF] = React.useState({
    name: p.name || "", id: p.id || "", type: p.type || "Ticket", desc: p.desc || "",
    trade: p.trade != null ? p.trade.toFixed(2) : "", rack: p.rack != null ? p.rack.toFixed(2) : "",
    stock: p.stock != null ? String(p.stock) : "", validity: "90", status: p.status || "Draft",
  });
  const set = (k) => (e) => { setF(prev => ({ ...prev, [k]: e.target.value })); setSubmitted(false); };
  const margin = (parseFloat(f.trade) && parseFloat(f.rack))
    ? Math.round((1 - parseFloat(f.trade) / parseFloat(f.rack)) * 100) : null;
  return (
    <div style={{ padding: 32, maxWidth: 880, margin: "0 auto" }}>
      <button onClick={onBack} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--orange-link)", fontWeight: 500, fontFamily: "var(--font-sans)", fontSize: 14, display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 18, padding: 0 }}><Icon name="arrow-left" size={16} />Back to products</button>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", gap: 24, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 16 }}>Product details</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Field label="Product name" required value={f.name} onChange={set("name")} placeholder="e.g. Cable Car Sky Pass" />
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="SKU" value={f.id} onChange={set("id")} placeholder="SKU-0000" />
                <Field label="Type" as="select" value={f.type} onChange={set("type")}>
                  <option>Ticket</option><option>Package</option><option>Experience</option><option>Charter</option>
                </Field>
              </div>
              <Field label="Description" as="textarea" value={f.desc} onChange={set("desc")} placeholder="Describe the product for trade buyers…" help="Plain language, sentence case. Avoid jargon and acronyms on first use." />
            </div>
          </Card>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 16 }}>Pricing &amp; inventory</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <Field label="Trade price (S$)" required value={f.trade} onChange={set("trade")} prefix="S$" placeholder="0.00" help="Excludes GST." />
              <Field label="Rack price (S$)" value={f.rack} onChange={set("rack")} prefix="S$" placeholder="0.00"
                help={margin != null ? `${margin}% trade discount` : undefined} />
              <Field label="Available stock" required value={f.stock} onChange={set("stock")} placeholder="0" />
              <Field label="Validity (days)" value={f.validity} onChange={set("validity")} />
            </div>
          </Card>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 18, position: "sticky", top: 88 }}>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 12 }}>Status</div>
            <Field as="select" value={f.status} onChange={set("status")}>
              <option>Draft</option><option>Live</option><option>Paused</option>
            </Field>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 16 }}>
              <Btn variant="primary" full icon="send" disabled={submitted || !f.name.trim()}
                onClick={() => { setSubmitted(true); window.toast("Submitted for SDC approval", "success", `${f.name} · queued for review`); }}>
                {submitted ? "Submitted for review" : "Submit for SDC approval"}
              </Btn>
              <Btn variant="secondary" full icon="save"
                onClick={() => window.toast("Draft saved", "info", `${f.name || "Untitled product"} · not yet submitted`)}>Save draft</Btn>
              <Btn variant="ghost" full onClick={onBack}>Cancel</Btn>
            </div>
          </Card>

          {/* Approval workflow - S/No. 133, 134; Reply 4 Q3, Q10 */}
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 4 }}>Approval workflow</div>
            <p className="caption" style={{ marginBottom: 14 }}>Products go live only after SDC review and onboarding into SnApp.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {[["Submitted by partner", submitted], ["SDC product review", false], ["Onboarded into SnApp", false], ["Live on marketplace", false]].map(([label, done], i, arr) => (
                <div key={label} style={{ display: "flex", gap: 11 }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "none" }}>
                    <span style={{ width: 20, height: 20, borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center",
                      background: done ? "var(--success)" : "var(--neutral-100)", border: done ? 0 : "1.5px solid var(--border-strong)" }}>
                      {done && <Icon name="check" size={12} color="#fff" strokeWidth={3} />}
                    </span>
                    {i < arr.length - 1 && <span style={{ width: 2, flex: 1, minHeight: 20, background: "var(--border)" }}></span>}
                  </div>
                  <div style={{ paddingBottom: i < arr.length - 1 ? 14 : 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: done ? 600 : 500, color: done ? "var(--fg1)" : "var(--fg2)" }}>{label}</div>
                    {i === 0 && submitted && <div style={{ fontSize: 12, color: "var(--fg2)" }}>Just now</div>}
                  </div>
                </div>
              ))}
            </div>
            {submitted && (
              <div style={{ marginTop: 14, display: "flex", gap: 9, padding: 12, background: "var(--success-bg)", borderRadius: "var(--radius-md)", fontSize: 12.5, color: "#0f5e35", lineHeight: 1.5 }}>
                <Icon name="check-circle" size={15} style={{ marginTop: 1, flex: "none" }} />
                Sent to the SDC product approval queue. You will be notified when it is reviewed.
              </div>
            )}
          </Card>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 8 }}>Product image</div>
            <button onClick={() => window.toast("Image uploaded", "success", "hero-1600x900.jpg · 412 KB")}
              style={{ width: "100%", height: 110, borderRadius: "var(--radius-md)", border: "1.5px dashed var(--border-strong)",
                display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 6,
                color: "var(--fg2)", background: "var(--neutral-50)", cursor: "pointer", fontFamily: "var(--font-sans)" }}>
              <Icon name="image-plus" size={24} color="var(--fg3)" /><span style={{ fontSize: 12.5 }}>Upload or drag image</span>
            </button>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardScreen, ProductsScreen, ProductEditor, OrdersTable, KpiCard, statusTone });
