/* Buyer validation portal — the page a buyer (e.g. Nordwind Logistics)
   lands on when they click the validation link. Standalone Aria-branded
   surface, NOT the Canopy ERP host. */

const _bvSvg = {
  x:       <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  shield:  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11 14 15 10"/></svg>,
  lock:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
  copy:    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>,
  check:   <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  check2:  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  info:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>,
  alert:   <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>,
  download:<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>,
  building:<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="2" width="18" height="20" rx="1"/><path d="M9 22v-4h6v4"/><line x1="8" y1="6" x2="8" y2="6"/><line x1="16" y1="6" x2="16" y2="6"/><line x1="12" y1="6" x2="12" y2="6"/><line x1="12" y1="10" x2="12" y2="10"/><line x1="8" y1="10" x2="8" y2="10"/><line x1="16" y1="10" x2="16" y2="10"/><line x1="12" y1="14" x2="12" y2="14"/><line x1="8" y1="14" x2="8" y2="14"/><line x1="16" y1="14" x2="16" y2="14"/></svg>,
};
const BvIcon = ({ n }) => _bvSvg[n] || null;

/* Invoice to present to the buyer. Uses a specific invoice if available,
   else a demo stub. */
const demoBuyerInvoice = {
  id: "INV-2026-0412",
  seller: "Boreal Studio SAS",
  sellerAddress: "24 rue de Turbigo · 75003 Paris · FR",
  sellerVat: "FR 42 894 217 310",
  buyer: "Nordwind Logistics GmbH",
  buyerContact: "Mira Hofmann",
  buyerAddress: "Leopoldstraße 112 · 80802 Munich · DE",
  buyerVat: "DE 287 431 982",
  issued: "Apr 22, 2026",
  due:    "May 22, 2026",
  terms:  "Net 30",
  po:     "PO-2026-0412",
  currency: "EUR",
  lines: [
    { d:"Design sprint — Identity system v2", qty: 1,  price: 8400.00 },
    { d:"Brand guidelines (40pp, EN/DE)",      qty: 1,  price: 2800.00 },
    { d:"Kick-off workshop (on-site, Munich)", qty: 2,  price:  650.00 },
  ],
  // original seller IBAN (now replaced by Aria's)
  originalIban: "FR76 3000 3012 3400 0284 7291 021",
  // Aria's dedicated payment IBAN for this assignment
  ariaIban:     "FR76 1695 8000 0104 1226 0983 01",
  ariaBic:      "QNTOFRP1XXX",
  ariaRef:      "ARIA-REF-0412-NRD",
};

const BuyerValidationPortal = ({ onClose, invoice }) => {
  const inv = invoice || demoBuyerInvoice;
  const [state, setState] = React.useState("pending"); // pending | confirming | done
  const [copiedIban, setCopiedIban] = React.useState(false);
  const [checked, setChecked] = React.useState(false);

  const subtotal = inv.lines.reduce((s,l)=>s+l.qty*l.price, 0);
  const vatRate = 0.20;
  const vat = subtotal * vatRate;
  const total = subtotal + vat;

  const copyIban = () => {
    try { navigator.clipboard.writeText(inv.ariaIban.replace(/\s/g,"")); } catch(e){}
    setCopiedIban(true);
    setTimeout(()=>setCopiedIban(false), 1600);
  };

  const confirm = () => {
    setState("confirming");
    setTimeout(()=>setState("done"), 900);
  };

  return (
    <div className="bv-portal">
      {/* Header */}
      <header className="bv-header">
        <div className="bv-header-inner">
          <div className="bv-header-brand">
            <img src="aria/logo_forest.png" alt="Aria" className="bv-logo"/>
            <span className="bv-header-divider"/>
            <div className="bv-header-title">
              <div className="bv-header-label">Buyer validation</div>
              <div className="bv-header-sub">Invoice assignment confirmation</div>
            </div>
          </div>
          <div className="bv-header-actions">
            <div className="bv-secure">
              <BvIcon n="lock"/>
              <span>aria.eu/validate · secure</span>
            </div>
            <button className="bv-close" onClick={onClose} title="Exit demo"><BvIcon n="x"/></button>
          </div>
        </div>
      </header>

      <main className="bv-main">
        {/* Left: the invoice */}
        <section className="bv-invoice">
          {/* Assignment banner at the top of the invoice */}
          <div className="bv-assign-banner">
            <div className="bv-assign-icon"><BvIcon n="shield"/></div>
            <div className="bv-assign-body">
              <div className="bv-assign-title">
                This invoice has been assigned to Aria SAS
              </div>
              <div className="bv-assign-sub">
                {inv.seller} has financed this receivable with Aria.
                Please settle this invoice to the <b>Aria IBAN below</b> — not to {inv.seller}'s original bank account.
                Your commercial relationship with {inv.seller} is unchanged.
              </div>
            </div>
          </div>

          <div className="bv-paper">
            <div className="bv-paper-head">
              <div>
                <div className="bv-paper-eyebrow">Invoice</div>
                <div className="bv-paper-id">{inv.id}</div>
              </div>
              <div className="bv-paper-dates">
                <div><span>Issued</span><b>{inv.issued}</b></div>
                <div><span>Due</span><b>{inv.due}</b></div>
                <div><span>Terms</span><b>{inv.terms}</b></div>
              </div>
            </div>

            <div className="bv-parties">
              <div>
                <div className="bv-party-label">From (Seller)</div>
                <div className="bv-party-name">{inv.seller}</div>
                <div className="bv-party-sub">{inv.sellerAddress}</div>
                <div className="bv-party-sub">VAT {inv.sellerVat}</div>
              </div>
              <div>
                <div className="bv-party-label">Bill to</div>
                <div className="bv-party-name">{inv.buyer}</div>
                <div className="bv-party-sub">{inv.buyerContact}</div>
                <div className="bv-party-sub">{inv.buyerAddress}</div>
                <div className="bv-party-sub">VAT {inv.buyerVat}</div>
              </div>
            </div>

            <table className="bv-lines">
              <thead><tr>
                <th>Description</th><th className="num">Qty</th><th className="num">Unit price</th><th className="num">Amount</th>
              </tr></thead>
              <tbody>
                {inv.lines.map((l,i)=>(
                  <tr key={i}>
                    <td>{l.d}</td>
                    <td className="num">{l.qty}</td>
                    <td className="num">{fmtEur(l.price)}</td>
                    <td className="num">{fmtEur(l.qty * l.price)}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            <div className="bv-totals">
              <div className="bv-totals-row"><span>Subtotal</span><b>{fmtEur(subtotal)}</b></div>
              <div className="bv-totals-row"><span>VAT (20%)</span><b>{fmtEur(vat)}</b></div>
              <div className="bv-totals-sep"/>
              <div className="bv-totals-row total"><span>Total due</span><b>{fmtEur(total)}</b></div>
            </div>

            {/* Payment instructions — replaces the usual "Pay to seller's IBAN" block */}
            <div className="bv-pay">
              <div className="bv-pay-head">
                <div>
                  <div className="bv-pay-title">Payment instructions</div>
                  <div className="bv-pay-sub">Pay the full amount to Aria's dedicated IBAN by {inv.due}.</div>
                </div>
                <div className="bv-pay-badge">
                  <img src="aria/logo_forest.png" alt="Aria"/>
                  <span>Payable to Aria</span>
                </div>
              </div>

              <div className="bv-iban-grid">
                <div className="bv-iban-row">
                  <div className="bv-iban-k">Beneficiary</div>
                  <div className="bv-iban-v">Aria SAS <span className="bv-iban-vsub">(on behalf of {inv.seller})</span></div>
                </div>
                <div className="bv-iban-row">
                  <div className="bv-iban-k">IBAN</div>
                  <div className="bv-iban-v bv-iban-mono">
                    {inv.ariaIban}
                    <button className="bv-iban-copy" onClick={copyIban}>
                      {copiedIban
                        ? (<><BvIcon n="check"/> Copied</>)
                        : (<><BvIcon n="copy"/> Copy</>)}
                    </button>
                  </div>
                </div>
                <div className="bv-iban-row">
                  <div className="bv-iban-k">BIC</div>
                  <div className="bv-iban-v bv-iban-mono">{inv.ariaBic}</div>
                </div>
                <div className="bv-iban-row">
                  <div className="bv-iban-k">Reference</div>
                  <div className="bv-iban-v bv-iban-mono">{inv.ariaRef}</div>
                </div>
              </div>

              <div className="bv-pay-warn">
                <BvIcon n="alert"/>
                <div>
                  <b>Do not pay the original IBAN</b> ({inv.originalIban.slice(0,14)}…). Paying it no longer settles this invoice — the receivable belongs to Aria until the due date.
                </div>
              </div>
            </div>

            <div className="bv-footer-note">
              Questions about the goods or services? Contact {inv.seller} directly at billing@borealstudio.eu.
              Questions about payment or Aria? Reply to this email or visit aria.eu/buyer-support.
            </div>
          </div>
        </section>

        {/* Right: confirmation panel */}
        <aside className="bv-side">
          {state !== "done" ? (
            <div className="bv-confirm">
              <div className="bv-confirm-head">
                <div className="bv-confirm-eyebrow">Confirm receipt</div>
                <div className="bv-confirm-title">Validate this invoice</div>
                <div className="bv-confirm-sub">
                  Please confirm you've received the goods/services and that you'll pay this invoice to Aria's IBAN by the due date.
                </div>
              </div>

              <div className="bv-summary">
                <div className="bv-summary-row">
                  <span>Invoice</span><b>{inv.id}</b>
                </div>
                <div className="bv-summary-row">
                  <span>From</span><b>{inv.seller}</b>
                </div>
                <div className="bv-summary-row">
                  <span>Due date</span><b>{inv.due}</b>
                </div>
                <div className="bv-summary-row big">
                  <span>Amount</span><b>{fmtEur(total)}</b>
                </div>
              </div>

              <label className="bv-check">
                <input type="checkbox" className="cb" checked={checked} onChange={e=>setChecked(e.target.checked)}/>
                <span>I confirm the invoice details are correct and that I will pay <b>{fmtEur(total)}</b> to Aria's IBAN by {inv.due}.</span>
              </label>

              <button className="bv-btn-primary" disabled={!checked || state==="confirming"} onClick={confirm}>
                {state === "confirming"
                  ? (<><span className="bv-spinner"/> Confirming…</>)
                  : (<>Validate & accept assignment</>)}
              </button>

              <div className="bv-trust">
                <BvIcon n="info"/>
                <span>Aria SAS · Funds escrowed in segregated accounts.</span>
              </div>

              <div className="bv-altrow">
                <button className="bv-link"><BvIcon n="download"/> Download PDF</button>
                <button className="bv-link"><BvIcon n="building"/> Pay via ERP</button>
              </div>
            </div>
          ) : (
            <div className="bv-confirm bv-done">
              <div className="bv-done-check"><BvIcon n="check2"/></div>
              <div className="bv-done-title">Invoice validated</div>
              <div className="bv-done-sub">
                Thanks, {inv.buyerContact.split(" ")[0]}. Your confirmation has been sent to {inv.seller} and Aria.
              </div>
              <div className="bv-done-next">
                <div className="bv-done-next-title">What happens next</div>
                <ol>
                  <li>Aria advances {inv.seller} within ~4 hours, less a 2% fee.</li>
                  <li>On <b>{inv.due}</b>, pay <b>{fmtEur(total)}</b> to Aria's IBAN above.</li>
                  <li>Aria closes the receivable — nothing else for you to do.</li>
                </ol>
              </div>
              <button className="bv-btn-secondary" onClick={onClose}>Return to demo</button>
            </div>
          )}
        </aside>
      </main>

      <footer className="bv-footer">
        <div className="bv-footer-inner">
          <div>Aria SAS · 24 rue du Faubourg Saint-Antoine, 75012 Paris · RCS Paris 894 217 310</div>
          <div className="bv-footer-links">
            <span>Privacy</span><span>Terms</span><span>Buyer support</span>
          </div>
        </div>
      </footer>
    </div>
  );
};

Object.assign(window, { BuyerValidationPortal });
