/* global React, MY_BILLS, BILLING_STATUS_META, fmtTHB,
   Avatar, StatusPill,
   IconReceipt, IconUpload, IconChevron, IconArrow, IconCheck, IconX,
   IconLock, IconFile, IconDownload, IconClock, IconBuilding, IconBank,
   IconPlus, IconSearch, IconDots, IconExt, IconChart, IconLogout, IconCal
*/
const { useState: useStateP } = React;

/* ============================================================
   SCREEN 6 — Supplier Portal: Login
   ============================================================ */
function ScreenLogin({ onLogin }) {
  return (
    <div className="portal-shell" data-theme="dark">
      <div className="portal-left">
        <div className="brand-lockup" style={{padding: 0}}>
          <img src="assets/logo-white.png" alt="MotionReach" style={{height: 24}}/>
          <div className="divider-v" style={{background: "rgba(255,255,255,0.2)", height: 22}}></div>
          <img className="brandstorm-mark" src="assets/brandstorm-white.png" alt="Brandstorm" style={{height: 22}}/>
        </div>
        <div className="portal-hero">
          <div className="t-eyebrow" style={{color: "var(--brand-cyan)", marginBottom: 18}}>Supplier Portal · MotionReach × Brandstorm</div>
          <h2>One inbox<br/>for the work and the money.</h2>
          <p>Submit invoices, track every approval step, and get paid faster. MotionReach and Brandstorm pay partners on real terms — and tell you exactly when.</p>
        </div>
        <div>
          <div className="portal-fact">
            <span className="big">3.4</span>
            <span>days average from invoice receipt to payment scheduled</span>
          </div>
          <div className="portal-fact">
            <span className="big">240+</span>
            <span>active suppliers across Bangkok &amp; Southeast Asia</span>
          </div>
          <div className="portal-fact">
            <span className="big">99.2%</span>
            <span>of paid invoices match supplier records on first pass</span>
          </div>
        </div>
      </div>
      <div className="portal-right">
        <form className="login-form" onSubmit={(e) => { e.preventDefault(); onLogin(); }}>
          <div>
            <h1>Welcome back</h1>
            <p className="sub">Sign in to your MotionReach supplier account</p>
          </div>

          <div className="field">
            <label className="field-label">Email or vendor ID</label>
            <input className="input" placeholder="billing@yourcompany.com" defaultValue="ops@tinkerpost.co.th"/>
          </div>

          <div className="field">
            <div style={{display:"flex", justifyContent:"space-between"}}>
              <label className="field-label">Password</label>
              <a href="#" style={{fontSize: 12, color: "var(--text-accent)", textDecoration: "none"}}>Forgot?</a>
            </div>
            <input className="input" type="password" defaultValue="••••••••••"/>
          </div>

          <div style={{display:"flex", alignItems:"center", gap: 8, fontSize: 13, color: "var(--text-secondary)"}}>
            <input type="checkbox" className="cb" defaultChecked/>
            <span>Keep me signed in on this device</span>
          </div>

          <button className="btn btn-primary btn-lg" style={{width: "100%"}}>
            Sign in <IconArrow size={14}/>
          </button>

          <div style={{height: 1, background: "var(--border-subtle)", margin: "4px 0"}}></div>

          <button type="button" className="btn btn-secondary btn-md" style={{width: "100%"}}>
            <IconLock size={14}/> Sign in with SSO
          </button>

          <div style={{textAlign: "center", fontSize: 12, color: "var(--text-tertiary)", marginTop: 4}}>
            Not registered yet? Reach out to your <a href="#" style={{color:"var(--text-accent)", textDecoration:"none"}}>MotionReach contact</a> to be onboarded.
          </div>
        </form>
      </div>
    </div>
  );
}

/* ============================================================
   SCREEN 7 — Submit billing (file upload + form)
   ============================================================ */
function ScreenSubmit({ onCancel, onSubmit }) {
  const [hasFile, setHasFile] = useStateP(false);

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-title-group">
          <h1>Submit invoice</h1>
          <div className="sub">Drop your PDF or photo — we'll match it to the PO and route to Project Manager review.</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost btn-sm" onClick={onCancel}>Cancel</button>
          <button className="btn btn-secondary btn-sm">Save draft</button>
          <button className="btn btn-primary btn-sm" onClick={onSubmit}><IconCheck size={14}/> Submit for review</button>
        </div>
      </div>

      <div style={{padding: "8px 24px 24px", display: "grid", gridTemplateColumns: "1fr 360px", gap: 24}}>
        <div style={{display:"flex", flexDirection:"column", gap: 16}}>
          <div className="section">
            <div className="section-head"><h3>1 — Invoice document</h3>
              <span className="muted" style={{fontSize: 12}}>PDF, JPG or PNG · max 20 MB</span>
            </div>
            <div className="section-body">
              {!hasFile ? (
                <div className="dropzone" onClick={() => setHasFile(true)}>
                  <div style={{
                    width: 52, height: 52, borderRadius: "50%",
                    background: "var(--accent-soft)",
                    color: "var(--accent)",
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    marginBottom: 12,
                  }}>
                    <IconUpload size={22}/>
                  </div>
                  <div className="big">Drop invoice file or click to browse</div>
                  <div className="small">We accept PDF (preferred), or photo of paper invoice. Multi-page OK.</div>
                </div>
              ) : (
                <div>
                  <div className="file-row" style={{borderColor: "var(--accent)", background: "var(--accent-soft)"}}>
                    <div className="file-icon" style={{background:"var(--accent)", color:"#fff"}}>pdf</div>
                    <div>
                      <div className="file-name">INV-2026-0518-tinkerpost.pdf</div>
                      <div className="file-meta">1.8 MB · uploaded just now · scanned & OCR'd</div>
                    </div>
                    <span className="pill pill-success"><IconCheck size={10}/> OCR complete</span>
                    <button className="icon-btn" onClick={() => setHasFile(false)}><IconX size={14}/></button>
                  </div>
                  <div style={{marginTop: 16, padding: 14, border: "1px dashed var(--border-default)", borderRadius: "var(--radius-md)", display:"flex", gap: 12, alignItems:"flex-start"}}>
                    <div style={{width: 24, height: 24, borderRadius:"50%", background:"var(--accent-soft)", color:"var(--accent)", display:"inline-flex", alignItems:"center", justifyContent:"center", flexShrink:0}}>
                      <IconCheck size={14}/>
                    </div>
                    <div style={{fontSize: 13, lineHeight: 1.5}}>
                      <div style={{fontWeight: 400}}>We detected the invoice details. Confirm or edit below.</div>
                      <div className="muted" style={{fontSize: 12, marginTop: 2}}>Auto-fields: number, date, amount, line items, tax breakdown</div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          <div className="section">
            <div className="section-head"><h3>2 — Match to PO</h3>
              <span className="muted" style={{fontSize: 12}}>Required — links the invoice to a project</span>
            </div>
            <div className="section-body">
              <div className="form-grid">
                <div className="field">
                  <label className="field-label">Purchase order <span style={{color:"var(--danger)"}}>*</span></label>
                  <div className="select">
                    <select defaultValue="PO-MR-3829 · Toyota Bz4X campaign">
                      <option>PO-MR-3829 · Toyota Bz4X campaign</option>
                      <option>PO-MR-3841 · Honda CR-V dealer push</option>
                      <option>PO-MR-3855 · Bangkok Bank Q2</option>
                    </select>
                  </div>
                </div>
                <div className="field">
                  <label className="field-label">Project</label>
                  <input className="input" defaultValue="Toyota Bz4X campaign — final mix" disabled/>
                  <span className="field-help">Inherited from PO. Read-only.</span>
                </div>
                <div className="field">
                  <label className="field-label">PO balance</label>
                  <input className="input" defaultValue="฿412,000 remaining of ฿820,000" disabled/>
                </div>
                <div className="field">
                  <label className="field-label">MotionReach contact</label>
                  <div style={{display:"flex", alignItems:"center", gap:10, padding: "8px 0"}}>
                    <Avatar name="Ploy Veerasakul" size="sm"/>
                    <div style={{display:"flex", flexDirection:"column"}}>
                      <span style={{fontSize: 13}}>Ploy Veerasakul</span>
                      <span className="muted" style={{fontSize: 11}}>Project Manager · approves your invoice first</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="section">
            <div className="section-head"><h3>3 — Confirm invoice details</h3>
              <span className="muted" style={{fontSize: 12}}>Auto-filled from your PDF</span>
            </div>
            <div className="section-body">
              <div className="form-grid">
                <div className="field">
                  <label className="field-label">Your invoice number <span style={{color:"var(--danger)"}}>*</span></label>
                  <input className="input" defaultValue="TP-2026-0418"/>
                </div>
                <div className="field">
                  <label className="field-label">Invoice date</label>
                  <input className="input" defaultValue="2026-04-18"/>
                </div>
                <div className="field">
                  <label className="field-label">Subtotal (THB)</label>
                  <input className="input" defaultValue="172,000.00"/>
                </div>
                <div className="field">
                  <label className="field-label">VAT 7%</label>
                  <input className="input" defaultValue="12,040.00"/>
                </div>
                <div className="field">
                  <label className="field-label">Withholding tax (3%)</label>
                  <input className="input" defaultValue="-5,160.00"/>
                </div>
                <div className="field">
                  <label className="field-label">Total due (THB)</label>
                  <input className="input" defaultValue="178,880.00" style={{fontWeight: 500}}/>
                </div>
                <div className="field full">
                  <label className="field-label">Line items <span className="muted">(3 detected)</span></label>
                  <div style={{border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", overflow: "hidden"}}>
                    <table className="tbl" style={{tableLayout: "auto"}}>
                      <thead>
                        <tr><th>Description</th><th className="right">Qty</th><th className="right">Rate</th><th className="right">Amount</th></tr>
                      </thead>
                      <tbody>
                        <tr><td>Final mix — 30s spot (3 versions)</td><td className="num right">3</td><td className="num right">{fmtTHB(28000)}</td><td className="num right">{fmtTHB(84000)}</td></tr>
                        <tr><td>Sound design — sting + transitions</td><td className="num right">1</td><td className="num right">{fmtTHB(56000)}</td><td className="num right">{fmtTHB(56000)}</td></tr>
                        <tr><td>Studio time — additional pickup</td><td className="num right">4</td><td className="num right">{fmtTHB(8000)}</td><td className="num right">{fmtTHB(32000)}</td></tr>
                      </tbody>
                    </table>
                  </div>
                </div>
                <div className="field full">
                  <label className="field-label">Note to MotionReach <span className="muted">(optional)</span></label>
                  <textarea className="input" placeholder="Anything we should flag for the reviewer? Schedule slips, scope changes…"/>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div style={{display:"flex", flexDirection:"column", gap: 16}}>
          <div className="section">
            <div className="section-head"><h3>Summary</h3></div>
            <div className="section-body">
              <dl className="kv" style={{gridTemplateColumns: "120px 1fr"}}>
                <dt>Vendor</dt><dd>Tinker Post Bangkok</dd>
                <dt>Vendor ID</dt><dd className="mono">VND-1042</dd>
                <dt>Terms</dt><dd className="mono">NET 45</dd>
                <dt>Expected pay-by</dt><dd className="mono">Jun 02, 2026</dd>
              </dl>
              <div className="hr"></div>
              <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline"}}>
                <div className="muted" style={{fontSize: 12}}>Total due</div>
                <div style={{fontSize: 28, fontWeight: 600, letterSpacing: "-0.01em", fontVariantNumeric: "tabular-nums"}}>{fmtTHB(178880)}</div>
              </div>
            </div>
          </div>

          <div className="section">
            <div className="section-head"><h3>What happens next</h3></div>
            <div className="section-body" style={{padding: "8px 18px 18px"}}>
              <div className="timeline">
                <div className="tl-item">
                  <div className="tl-marker"><span className="dot done"></span></div>
                  <div className="tl-body">
                    <div className="when">NOW</div>
                    <div className="what">Submitted by you</div>
                    <div className="who">Routed automatically — no email needed</div>
                  </div>
                </div>
                <div className="tl-item">
                  <div className="tl-marker"><span className="dot"></span></div>
                  <div className="tl-body">
                    <div className="when">~24h</div>
                    <div className="what">PM verifies against PO</div>
                    <div className="who">Ploy V. — Project Manager</div>
                  </div>
                </div>
                <div className="tl-item">
                  <div className="tl-marker"><span className="dot pending"></span></div>
                  <div className="tl-body">
                    <div className="when">~3 days</div>
                    <div className="what">Finance verifies tax + bank match</div>
                    <div className="who">Ananda V. — Accounting</div>
                  </div>
                </div>
                <div className="tl-item">
                  <div className="tl-marker"><span className="dot pending"></span></div>
                  <div className="tl-body">
                    <div className="when">Jun 02</div>
                    <div className="what">Payment released to your account</div>
                    <div className="who">Per your NET 45 terms</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="section">
            <div className="section-head"><h3>Need help?</h3></div>
            <div className="section-body" style={{fontSize: 13, color: "var(--text-secondary)", lineHeight: 1.6}}>
              If your invoice doesn't match a PO, contact <a href="#" style={{color:"var(--text-accent)", textDecoration:"none"}}>ap@motionreach.co</a> or your MotionReach project manager directly.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   SCREEN 8 — Supplier portal billing status tracker
   ============================================================ */
function ScreenPortalBilling({ onSubmit }) {
  const [openIdx, setOpenIdx] = useStateP(3); // open the pm-review one by default

  const open = MY_BILLS[openIdx];
  const stages = [
    { key: "submitted",      label: "Submitted",       when: "Apr 22 · 09:14" },
    { key: "pm-review",      label: "PM review",       when: "Apr 22 · 11:02", actor: "Ploy V."     },
    { key: "finance-verify", label: "Finance verify",  when: null },
    { key: "approved-payment",label:"Approved",        when: null },
    { key: "scheduled",      label: "Scheduled",       when: null },
    { key: "paid",           label: "Paid",            when: null },
  ];
  // Determine progress based on status
  const order = ["submitted","pm-review","finance-verify","approved-payment","scheduled","paid"];
  const progressIdx = order.indexOf(open.status);

  // Totals
  const totals = MY_BILLS.reduce((acc, b) => {
    if (b.status === "paid") acc.paid += b.amount;
    else if (b.status === "approved-payment" || b.status === "scheduled") acc.approved += b.amount;
    else if (b.status === "rejected" || b.status === "disputed") acc.disputed += b.amount;
    else acc.pending += b.amount;
    return acc;
  }, { paid: 0, approved: 0, pending: 0, disputed: 0 });

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-title-group">
          <h1>My billing</h1>
          <div className="sub">All invoices submitted to MotionReach · synced just now</div>
        </div>
        <div className="page-actions">
          <button className="btn btn-secondary btn-sm"><IconDownload size={14}/> Statement</button>
          <button className="btn btn-primary btn-sm" onClick={onSubmit}><IconPlus size={14}/> New invoice</button>
        </div>
      </div>

      <div className="stat-row">
        <div className="stat-tile">
          <div className="label">Awaiting review</div>
          <div className="val tnum">{fmtTHB(totals.pending)}</div>
          <div className="delta">3 invoices in progress</div>
        </div>
        <div className="stat-tile">
          <div className="label">Approved · awaiting pay</div>
          <div className="val tnum" style={{color: "var(--info)"}}>{fmtTHB(totals.approved)}</div>
          <div className="delta">2 invoices scheduled</div>
        </div>
        <div className="stat-tile">
          <div className="label">Paid YTD</div>
          <div className="val tnum">{fmtTHB(totals.paid)}</div>
          <div className="delta">12 invoices · avg 4.1 days</div>
        </div>
        <div className="stat-tile">
          <div className="label">Disputed / rejected</div>
          <div className="val tnum" style={{color: "var(--danger)"}}>{fmtTHB(totals.disputed)}</div>
          <div className="delta down">2 needs your input</div>
        </div>
      </div>

      <div style={{display: "grid", gridTemplateColumns: "1fr 440px", flex: 1, overflow: "hidden", borderTop: "1px solid var(--border-subtle)"}}>
        <div style={{overflowY:"auto"}}>
          <div className="toolbar" style={{borderTop: "none"}}>
            <button className="chip active">All <span className="muted">{MY_BILLS.length}</span></button>
            <button className="chip">In review <span className="muted">3</span></button>
            <button className="chip">Approved <span className="muted">2</span></button>
            <button className="chip">Paid <span className="muted">2</span></button>
            <button className="chip">Needs attention <span className="muted">2</span></button>
            <div className="toolbar-right">
              <div className="topbar-search" style={{maxWidth: 200, margin: 0}}>
                <IconSearch size={14} className="icon"/>
                <input placeholder="Search invoices…"/>
              </div>
            </div>
          </div>

          <table className="tbl">
            <colgroup>
              <col style={{width: 160}}/>
              <col style={{width: 130}}/>
              <col/>
              <col style={{width: 120}}/>
              <col style={{width: 100}}/>
              <col style={{width: 160}}/>
              <col style={{width: 36}}/>
            </colgroup>
            <thead>
              <tr>
                <th>Invoice</th>
                <th>PO</th>
                <th>Project</th>
                <th className="right">Amount</th>
                <th>Submitted</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {MY_BILLS.map((b, i) => (
                <tr key={b.id}
                  onClick={() => setOpenIdx(i)}
                  className={i === openIdx ? "selected" : ""}
                  style={{cursor: "pointer"}}>
                  <td className="mono" style={{color: "var(--text-primary)"}}>{b.id}</td>
                  <td className="mono muted">{b.po}</td>
                  <td className="ellipsis">{b.project}</td>
                  <td className="num right tnum">{fmtTHB(b.amount)}</td>
                  <td className="muted" style={{fontSize: 12}}>{b.submitted}</td>
                  <td><StatusPill meta={BILLING_STATUS_META[b.status]}/></td>
                  <td><button className="icon-btn"><IconChevron size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={{borderLeft: "1px solid var(--border-subtle)", background: "var(--bg-secondary)", overflowY: "auto", padding: 20}}>
          <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom: 16}}>
            <div>
              <div style={{fontSize: 11, color: "var(--text-tertiary)", textTransform: "uppercase", letterSpacing: "0.08em"}}>Invoice</div>
              <div style={{fontFamily: "var(--font-mono)", fontSize: 16, fontWeight: 500, marginTop: 4}}>{open.id}</div>
            </div>
            <StatusPill meta={BILLING_STATUS_META[open.status]}/>
          </div>

          <div style={{
            background: "var(--bg-primary)",
            borderRadius: "var(--radius-md)",
            padding: 16,
            border: "1px solid var(--border-subtle)",
            marginBottom: 16,
          }}>
            <div className="muted" style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em"}}>Amount due</div>
            <div style={{fontSize: 30, fontWeight: 600, letterSpacing: "-0.01em", fontVariantNumeric: "tabular-nums", marginTop: 4}}>
              {fmtTHB(open.amount)}
            </div>
            <div style={{marginTop: 6, fontSize: 12, color: "var(--text-tertiary)"}}>
              Project: <span style={{color: "var(--text-secondary)"}}>{open.project}</span>
            </div>
            <div style={{marginTop: 2, fontSize: 12, color: "var(--text-tertiary)"}}>
              PO: <span className="mono" style={{color: "var(--text-secondary)"}}>{open.po}</span> · Due: <span className="mono" style={{color: "var(--text-secondary)"}}>{open.due}</span>
            </div>
          </div>

          <div style={{fontSize: 11, color: "var(--text-tertiary)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 12}}>Progress</div>
          <div className="timeline">
            {stages.map((st, i) => {
              const done = i <= progressIdx;
              const current = i === progressIdx + 1;
              const cls = done ? "done" : (current ? "" : "pending");
              return (
                <div key={st.key} className="tl-item">
                  <div className="tl-marker"><span className={"dot " + cls}></span></div>
                  <div className="tl-body">
                    <div className="when">{st.when || (done ? "" : current ? "in progress" : "—")}</div>
                    <div className="what" style={{color: done || current ? "var(--text-primary)" : "var(--text-tertiary)"}}>{st.label}</div>
                    {st.actor && <div className="who">{st.actor}</div>}
                  </div>
                </div>
              );
            })}
          </div>

          {open.status === "disputed" && (
            <div style={{
              marginTop: 16,
              padding: 14,
              background: "color-mix(in oklab, var(--warning) 14%, transparent)",
              borderRadius: "var(--radius-md)",
              borderLeft: "3px solid var(--warning)",
            }}>
              <div style={{fontSize: 13, fontWeight: 400, marginBottom: 4, color: "var(--warning)"}}>Dispute opened — needs your input</div>
              <div style={{fontSize: 12, color: "var(--text-secondary)", lineHeight: 1.5}}>
                "Line item 2 quantity doesn't match the delivery note. Can you confirm the 4 pickup hours were actually used?" — Ananda V., Finance
              </div>
              <button className="btn btn-primary btn-sm" style={{marginTop: 12}}>Reply with documentation</button>
            </div>
          )}

          <div className="hr"></div>

          <div style={{fontSize: 11, color: "var(--text-tertiary)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 10}}>Attachments</div>
          <div className="file-row">
            <div className="file-icon">pdf</div>
            <div>
              <div className="file-name">{open.id}.pdf</div>
              <div className="file-meta">1.8 MB · uploaded by you</div>
            </div>
            <button className="icon-btn"><IconDownload size={14}/></button>
            <button className="icon-btn"><IconExt size={14}/></button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenLogin, ScreenSubmit, ScreenPortalBilling });
