/* global React, Icon, Pill, SrcChip, Field, QUOTES, NEEDS_ROUTING, REPS, DEPOTS, TRANSPORT */
const { useState, useMemo } = React;

function SalesView({ flow, advanceFlow }) {
  const [screen, setScreen] = useState("inbox");  // inbox | detail | delivery | performance
  const [activeQuote, setActiveQuote] = useState(QUOTES[0]);
  const [templated, setTemplated] = useState(false);
  const [sent, setSent] = useState(false);

  // Flow driver — moves the sales rep through the quote→delivery steps
  useEffect(() => {
    if (!flow || flow.id !== "quote-to-delivery") return;
    if (flow.step === 0) setScreen("inbox");
    if (flow.step === 1) { setActiveQuote(QUOTES[0]); setScreen("detail"); setTemplated(false); setSent(false); }
    if (flow.step === 2) { setTemplated(true); }
  }, [flow?.step]);

  return (
    <div className="view-inner">
      <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div className="row" style={{ gap: 8 }}>
            <h2 className="page-title">Sales · John Harrow</h2>
            <Pill tone="info" noDot>Christchurch / South Island</Pill>
          </div>
          <p className="page-sub">Your region's quotes, sales orders and delivery requests — no shared-inbox noise.</p>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <button className={`btn ${screen === "inbox" ? "primary" : ""}`} onClick={() => setScreen("inbox")}><Icon name="inbox" size={14} /> Quote inbox</button>
          <button className={`btn ${screen === "performance" ? "primary" : ""}`} onClick={() => setScreen("performance")}><Icon name="trending" size={14} /> My week</button>
        </div>
      </div>

      {screen === "inbox" && <QuoteInbox onOpen={(q) => { setActiveQuote(q); setTemplated(false); setSent(false); setScreen("detail"); }} />}
      {screen === "detail" && <QuoteDetail q={activeQuote} templated={templated} onTemplate={() => setTemplated(true)} sent={sent} onSend={() => { setSent(true); if (flow?.id === "quote-to-delivery" && flow.step === 2) advanceFlow(); }} onBack={() => setScreen("inbox")} onDelivery={() => setScreen("delivery")} flowHint={flow?.id === "quote-to-delivery" ? flow.step : null} />}
      {screen === "delivery" && <DeliveryRequest onBack={() => setScreen("detail")} onSent={() => { setScreen("inbox"); if (flow?.id === "quote-to-delivery") advanceFlow(); }} flowActive={flow?.id === "quote-to-delivery"} />}
      {screen === "performance" && <PerformanceCard />}
    </div>
  );
}

function QuoteInbox({ onOpen }) {
  const toneFromSla = s => s === "ok" ? "ok" : s === "warn" ? "warn" : "err";
  const labelFromSla = s => s === "ok" ? "On track" : s === "warn" ? "Closing in" : "Breached";

  return (
    <>
      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginBottom: 16 }}>
        <KpiChip label="In your inbox"           value="6" sub="2 newer than 4h" />
        <KpiChip label="Response time (wk)"      value="1.3d" sub="target 0.5d" tone="warn" />
        <KpiChip label="Sent this week"          value="11" sub="+2 vs last wk" />
        <KpiChip label="Conversion rate (30d)"   value="46%" sub="source: website 52%, phone 38%" />
      </div>

      <div className="card mb-16">
        <div className="card-head">
          <h3>My quote inbox</h3><span className="count">· 6 · assigned by postcode rule</span>
          <div className="right">
            <button className="btn sm"><Icon name="filter" size={12} /> Filter</button>
            <button className="btn sm"><Icon name="sort" size={12} /> Sort: newest</button>
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 110 }}>Quote</th>
              <th>Customer</th>
              <th>Container</th>
              <th>Source</th>
              <th>Submitted</th>
              <th>SLA clock</th>
              <th style={{ width: 60 }}></th>
            </tr>
          </thead>
          <tbody>
            {QUOTES.map((q, i) => (
              <tr key={q.id} onClick={() => onOpen(q)} style={{ cursor: "pointer" }} className="slide-in" styles={{ animationDelay: `${i * 20}ms` }}>
                <td><span className="mono" style={{ fontWeight: 600 }}>{q.id}</span></td>
                <td>
                  <div className="row-label">{q.customer}</div>
                  <div className="row-meta">{q.note}{q.missing.length ? <span style={{ color: "var(--warn)" }}> · {q.missing.length} missing field{q.missing.length>1?"s":""}</span> : ""}</div>
                </td>
                <td><span className="mono">{q.qty}× {q.type}</span></td>
                <td><SrcChip src={q.source} /></td>
                <td><span className="muted">{q.submitted}</span></td>
                <td><Pill tone={toneFromSla(q.sla)} noDot>{labelFromSla(q.sla)}</Pill></td>
                <td><Icon name="chev_r" size={14} style={{ color: "var(--ink-400)" }} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="card">
        <div className="card-head">
          <h3>Needs routing</h3><span className="count">· 2 · no rep for this postcode</span>
          <div className="right">
            <Pill tone="warn" noDot>Routing rule review?</Pill>
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr><th>Quote</th><th>Customer</th><th>Postcode</th><th>Suggested rep</th><th></th></tr>
          </thead>
          <tbody>
            {NEEDS_ROUTING.map(q => (
              <tr key={q.id}>
                <td><span className="mono">{q.id}</span></td>
                <td><div className="row-label">{q.customer}</div><div className="row-meta">{q.note}</div></td>
                <td><span className="mono">{q.postcode}</span></td>
                <td><span className="muted">{q.postcode.startsWith("9") ? "Kiri Johansen" : "Mere Wātene"} (nearest)</span></td>
                <td><button className="btn sm">Assign</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function KpiChip({ label, value, sub, tone }) {
  return (
    <div className="card" style={{ padding: "12px 14px" }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--ink-500)" }}>{label}</div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 22, fontWeight: 600, marginTop: 4, color: tone === "warn" ? "var(--warn)" : "var(--ink-900)" }}>{value}</div>
      <div style={{ fontSize: 11.5, color: "var(--ink-500)", marginTop: 2 }}>{sub}</div>
    </div>
  );
}

function QuoteDetail({ q, templated, onTemplate, sent, onSend, onBack, onDelivery, flowHint }) {
  const [poaResolved, setPoaResolved] = useState(false);
  return (
    <>
      <div className="row mb-12" style={{ gap: 8 }}>
        <button className="btn ghost sm" onClick={onBack}><Icon name="chev_r" size={12} style={{ transform: "rotate(180deg)" }} /> Back to inbox</button>
        <span className="muted">·</span>
        <span className="mono muted">{q.id}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16, alignItems: "start" }}>
        <div className="card">
          <div className="card-head">
            <h3>{q.customer}</h3>
            <Pill tone="info" noDot>Quote request</Pill>
            <div className="right">
              <SrcChip src="Website" /><SrcChip src="Cin7" />
            </div>
          </div>
          <div style={{ padding: 16, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <Field label="Contact name" src="Website">Pete Rangi</Field>
            <Field label="Phone" src="Website">+64 27 555 0142</Field>
            <Field label="Email" src="Website">pete@rangitata-orchards.co.nz</Field>
            <Field label="Delivery postcode" src="Website">{q.postcode} <Pill tone="info" noDot className="mono" style={{ marginLeft: 6 }}>Rangitata</Pill></Field>
            <Field label="Requested" src="Website"><span className="mono">{q.qty}× {q.type}</span></Field>
            <Field label="Use case" src="Website">{q.note}</Field>
          </div>

          {q.missing.length > 0 && (
            <div style={{ margin: "0 16px 16px", padding: 12, border: "1px dashed var(--warn)", borderRadius: 8, background: "var(--warn-bg)" }}>
              <div className="row" style={{ gap: 8 }}>
                <Icon name="warn" size={14} style={{ color: "var(--warn)" }} />
                <strong style={{ color: "var(--warn)" }}>{q.missing.length} field{q.missing.length>1?"s":""} missing from the web form</strong>
              </div>
              <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>
                {q.missing.join(" · ")} — the template will ask for these before sending.
              </div>
            </div>
          )}

          {/* POA resolver */}
          {q.id === "Q-18402" && !poaResolved && (
            <div style={{ margin: "0 16px 16px", padding: 12, border: "1px solid var(--line)", borderRadius: 8, background: "var(--ink-50)" }}>
              <div className="row" style={{ gap: 8 }}>
                <Icon name="pin" size={14} />
                <strong style={{ fontSize: 13 }}>Resolve POA postcode</strong>
                <span className="muted" style={{ fontSize: 12 }}>Transport for 7910 flagged as "price on application" in the matrix.</span>
              </div>
              <div className="row mt-8" style={{ gap: 8 }}>
                <input placeholder="192 Port Loop Rd, Timaru 7910" style={{ flex: 1, height: 30, padding: "0 10px", border: "1px solid var(--line)", borderRadius: 6, background: "var(--card)" }} />
                <button className="btn primary sm" onClick={() => setPoaResolved(true)}>Look up</button>
              </div>
            </div>
          )}
        </div>

        <div className="card">
          <div className="card-head">
            <h3>Build the quote</h3>
            {templated && <Pill tone="ok" noDot>Template applied</Pill>}
          </div>
          <div style={{ padding: 16 }}>
            {!templated ? (
              <>
                <p className="muted" style={{ fontSize: 12.5, marginTop: 0 }}>
                  The web form gave you a bare request. Apply your template to add accessories, notations, and transport from the postcode matrix.
                </p>
                <button className="btn primary" onClick={onTemplate} style={{ width: "100%", justifyContent: "center" }}>
                  <Icon name="bolt" size={14} /> Apply "Sale – Standard" template
                </button>
                {flowHint === 1 && <div className="flow-hint">Step 2 · apply the template</div>}
              </>
            ) : (
              <>
                <LineItem name={`${q.qty}× ${q.type} container`} price={`$${(q.qty * 4200).toLocaleString()}.00`} src="Cin7" />
                <LineItem name="Heavy-duty padlock (2)" price="$89.00" src="Cin7" />
                <LineItem name="Vent kit" price="$120.00" src="Cin7" />
                <LineItem name={`Transport — ${q.postcode}`} price="$480.00" src="Hub" sub="postcode matrix" />
                <div style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderTop: "1px solid var(--line)", marginTop: 8 }}>
                  <strong>Total (ex GST)</strong>
                  <strong className="mono">${((q.qty * 4200) + 89 + 120 + 480).toLocaleString()}.00</strong>
                </div>
                <div className="row mt-12" style={{ gap: 8 }}>
                  {!sent ? (
                    <button className="btn primary" style={{ width: "100%", justifyContent: "center" }} onClick={onSend}>
                      <Icon name="mail" size={14} /> Send quote to {q.customer}
                    </button>
                  ) : (
                    <div style={{ display: "flex", flexDirection: "column", gap: 10, width: "100%" }}>
                      <Pill tone="ok" noDot style={{ alignSelf: "flex-start" }}>Sent via Xero · logged to Cin7</Pill>
                      <button className="btn dark" style={{ justifyContent: "center" }} onClick={onDelivery}>
                        Simulate: customer accepted → book delivery <Icon name="arrow" size={13} />
                      </button>
                    </div>
                  )}
                </div>
                {flowHint === 2 && !sent && <div className="flow-hint">Step 3 · send the quote</div>}
              </>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

function LineItem({ name, price, src, sub }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid var(--line-soft)", fontSize: 13 }}>
      <div>
        <div>{name} <SrcChip src={src} /></div>
        {sub && <div className="muted" style={{ fontSize: 11 }}>{sub}</div>}
      </div>
      <span className="mono">{price}</span>
    </div>
  );
}

function DeliveryRequest({ onBack, onSent, flowActive }) {
  const [partner, setPartner] = useState("lion");
  const [extra, setExtra] = useState("Drop on concrete pad near shed. Gate code 4421. Pete on site from 8.");
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  const fire = () => {
    setSending(true);
    setTimeout(() => { setSent(true); setSending(false); }, 900);
  };

  return (
    <>
      <div className="row mb-12">
        <button className="btn ghost sm" onClick={onBack}><Icon name="chev_r" size={12} style={{ transform: "rotate(180deg)" }} /> Back</button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 16, alignItems: "start" }}>
        <div className="card">
          <div className="card-head">
            <h3>Send delivery request</h3>
            <Pill tone="info" noDot>Replaces the WeCare email</Pill>
          </div>
          <div style={{ padding: 16, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="Sales order" src="Cin7" big><span className="mono">SO-44215</span></Field>
            <Field label="Customer" src="Cin7">Rangitata Orchards Ltd</Field>
            <Field label="Delivery address" src="Cin7" style={{ gridColumn: "span 2" }}>142 Arundel Rakaia Gorge Rd, Rangitata 7782</Field>
            <Field label="Site contact" src="Cin7">Pete Rangi · +64 27 555 0142</Field>
            <Field label="Release number" src="Cin7"><span className="mono">REL-88421</span></Field>
            <Field label="Container SKU" src="Cin7"><span className="mono">SCNU-4820931</span> · 20ft Std</Field>
            <Field label="From depot" src="Cin7">Christchurch</Field>

            <div style={{ gridColumn: "span 2" }}>
              <div className="field-label"><span>Transport partner</span><SrcChip src="Hub" /></div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 6 }}>
                {TRANSPORT.slice(0, 3).map(t => (
                  <button key={t.id} onClick={() => setPartner(t.id)} className="btn" style={{
                    height: 48, justifyContent: "flex-start", padding: "0 12px",
                    borderColor: partner === t.id ? "var(--brand-cyan)" : "var(--line)",
                    background: partner === t.id ? "var(--brand-cyan-50)" : "var(--card)",
                    color: "var(--ink-900)",
                  }}>
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 12.5, fontWeight: 700 }}>{t.name}</div>
                      <div style={{ fontSize: 10.5, color: "var(--ink-500)", fontWeight: 500 }}>{t.region} · {t.reliability === "good" ? "reliable" : "watch"}</div>
                    </div>
                  </button>
                ))}
              </div>
            </div>

            <div style={{ gridColumn: "span 2" }}>
              <div className="field-label">Notes for the driver</div>
              <textarea value={extra} onChange={e => setExtra(e.target.value)} style={{
                width: "100%", minHeight: 70, resize: "vertical",
                padding: 10, border: "1px solid var(--line)", borderRadius: 6, background: "var(--card)"
              }} />
            </div>
          </div>
          <div style={{ padding: 16, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
            <button className="btn" onClick={onBack}>Cancel</button>
            {!sent ? (
              <button className="btn primary" onClick={fire} disabled={sending}>
                {sending ? <>Sending…</> : <><Icon name="play" size={13} /> Send to transport partner</>}
              </button>
            ) : (
              <Pill tone="ok" noDot>Sent · SMS to Lion Crane + customer</Pill>
            )}
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>What this will do</h3>
          </div>
          <div style={{ padding: 16 }}>
            <Consequence ok={sent} icon="doc" t="Create delivery job DJ-20421"    s="Visible to customer services inbox" />
            <Consequence ok={sent} icon="phone" t="SMS Lion Crane with secure link" s="Accept / Decline / Amend date" />
            <Consequence ok={sent} icon="mail" t="SMS end customer"                 s="‘You'll get updates for this delivery.’" />
            <Consequence ok={sent} icon="dashboard" t="Add to leadership board"     s="In-flight deliveries · today" />

            {sent && (
              <button className="btn dark mt-12" style={{ width: "100%", justifyContent: "center" }} onClick={onSent}>
                {flowActive ? "Continue flow →" : "Back to inbox"}
              </button>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

function Consequence({ ok, icon, t, s }) {
  return (
    <div className="row" style={{ padding: "8px 0", borderBottom: "1px solid var(--line-soft)", gap: 10, alignItems: "flex-start" }}>
      <div style={{ width: 24, height: 24, borderRadius: 6, background: ok ? "var(--ok-bg)" : "var(--ink-100)", color: ok ? "var(--ok)" : "var(--ink-500)", display: "grid", placeItems: "center", flex: "none" }}>
        {ok ? <Icon name="check" size={13} /> : <Icon name={icon} size={13} />}
      </div>
      <div style={{ fontSize: 12.5 }}>
        <div style={{ fontWeight: 600 }}>{t}</div>
        <div className="muted" style={{ fontSize: 11.5 }}>{s}</div>
      </div>
    </div>
  );
}

function PerformanceCard() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
      <div className="card" style={{ padding: 18 }}>
        <h3 style={{ margin: 0, fontSize: 14 }}>My week · quote-to-quote-sent</h3>
        <p className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>Replaces the 45-min Friday Excel report.</p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginTop: 16 }}>
          <Stat label="Quotes received" v="14" />
          <Stat label="Quotes sent"     v="11" />
          <Stat label="Avg response"    v="1.3d" tone="warn" />
          <Stat label="Conversion"      v="46%" />
        </div>
        <div style={{ marginTop: 18 }}>
          <BarChart />
        </div>
      </div>
      <div className="card" style={{ padding: 18 }}>
        <h3 style={{ margin: 0, fontSize: 14 }}>Source mix (30d)</h3>
        <p className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>Website quotes convert higher.</p>
        <Donut />
      </div>
    </div>
  );
}

function Stat({ label, v, tone }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 700 }}>{label}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 600, color: tone === "warn" ? "var(--warn)" : "var(--ink-900)" }}>{v}</div>
    </div>
  );
}

function BarChart() {
  const data = [3, 2, 4, 2, 3, 0, 0];  // Mon–Sun
  const labels = ["M","T","W","T","F","S","S"];
  const max = 5;
  return (
    <div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 8, height: 80 }}>
        {data.map((v, i) => (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
            <div style={{ width: "100%", height: `${(v/max)*100}%`, background: v ? "var(--brand-cyan)" : "var(--ink-100)", borderRadius: 4, minHeight: 4 }} />
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-500)" }}>{labels[i]}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Donut() {
  const online = 62, phone = 38;
  const r = 40, c = 2*Math.PI*r;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 24, marginTop: 18 }}>
      <svg width="120" height="120" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r={r} fill="none" stroke="var(--ink-100)" strokeWidth="14" />
        <circle cx="50" cy="50" r={r} fill="none" stroke="var(--brand-cyan)" strokeWidth="14"
          strokeDasharray={`${(online/100)*c} ${c}`} strokeDashoffset={c*0.25} transform="rotate(-90 50 50)" strokeLinecap="butt" />
        <text x="50" y="54" textAnchor="middle" style={{ fontSize: 14, fontWeight: 700, fill: "var(--ink-900)", fontFamily: "var(--font-mono)" }}>{online}%</text>
      </svg>
      <div>
        <div className="row" style={{ gap: 8, fontSize: 13 }}><span style={{ width:10, height:10, borderRadius: 2, background: "var(--brand-cyan)" }} /> Website <span className="mono muted">{online}% · 52% conv</span></div>
        <div className="row mt-8" style={{ gap: 8, fontSize: 13 }}><span style={{ width:10, height:10, borderRadius: 2, background: "var(--ink-100)" }} /> Phone <span className="mono muted">{phone}% · 38% conv</span></div>
      </div>
    </div>
  );
}

window.SalesView = SalesView;
