/* Canopy ERP — New Invoice modal with optional "Get paid now" handoff.
   Uses inline SVG icons (not lucide) to avoid DOM conflicts with the
   global lucide.createIcons() effect. */

const _svg = {
  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>,
  check:     <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  caret:     <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>,
  lock:      <svg width="13" height="13" 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>,
  zap:       <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>,
  info:      <svg width="13" height="13" 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>,
  arrowR:    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
  send:      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>,
  "file-text":         <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>,
  "clipboard-check":   <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="8" y="2" width="8" height="4" rx="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><polyline points="9 14 11 16 15 12"/></svg>,
  "package-check":     <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 16l2 2 4-4"/><path d="M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0"/><polyline points="3.3 7 12 12 20.7 7"/></svg>,
  truck:     <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>,
  file:      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>,
};
const Icon = ({ n, size, color }) => {
  const el = _svg[n] || _svg.file;
  const style = {};
  if (size) { style.width = size; style.height = size; }
  if (color) style.color = color;
  return React.cloneElement(el, { style: {...el.props.style, ...style} });
};

const NewInvoiceModal = ({ onClose, onCreate, onCreateAndFinance }) => {
  const [step, setStep] = React.useState(1);
  const [buyer, setBuyer] = React.useState(CLIENTS[0]?.name || "");
  const [buyerSub, setBuyerSub] = React.useState(CLIENTS[0]?.city || "");
  const [amount, setAmount] = React.useState("12500.00");
  const [terms, setTerms] = React.useState("Net 30");
  const [validation, setValidation] = React.useState("buyer");
  const [docs, setDocs] = React.useState(["invoice","order","pod"]);
  const [note, setNote] = React.useState("Delivery completed — reference PO-2026-0412.");
  const [financeNow, setFinanceNow] = React.useState(false);

  const pickClient = (name) => {
    setBuyer(name);
    const c = CLIENTS.find(x=>x.name===name);
    if (c) { setBuyerSub(c.city); setTerms(c.terms); }
  };
  const toggleDoc = (d) => setDocs(prev => prev.includes(d) ? prev.filter(x=>x!==d) : [...prev, d]);

  const amt = parseFloat(amount.replace(/[^0-9.]/g,"")) || 0;
  const fee = amt * (ARIA_TERMS?.feeRate || 0.02);
  const payout = amt - fee;
  const termsDays = parseInt((terms.match(/\d+/)||[30])[0],10);

  const buildInvoice = () => ({
    id: `INV-2026-0${413 + Math.floor(Math.random()*80)}`,
    buyer, buyerSub,
    amount: amt,
    dueIn: termsDays,
    issued: "Apr 24, 2026",
    terms, status: "pending", validation, docs,
  });

  const valid = buyer && amt > 0;
  const handleCreate = () => {
    const inv = buildInvoice();
    if (financeNow) onCreateAndFinance(inv); else onCreate(inv);
  };

  const docOptions = [
    { id:"invoice", label:"Invoice PDF",       icon:"file-text" },
    { id:"order",   label:"Order proof",       icon:"clipboard-check" },
    { id:"pod",     label:"Proof of delivery", icon:"package-check" },
    { id:"ecmr",    label:"e-CMR",             icon:"truck" },
  ];

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal new-inv-modal" onClick={e=>e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h2 className="modal-head-title">{step===1 ? "New invoice" : "Review & send"}</h2>
            <div className="modal-head-sub">
              {step===1 ? "Bill a client — optionally advance it with Aria in the same flow." : "Confirm the details before sending."}
            </div>
          </div>
          <button className="modal-close" onClick={onClose}><Icon n="x"/></button>
        </div>

        <div className="modal-stepper">
          <div className={"stepper-step"+(step===1?" active":"")+(step>1?" done":"")}>
            <div className="stepper-dot">{step>1 ? <Icon n="check"/> : 1}</div>
            <span>Details</span>
          </div>
          <div className={"stepper-line"+(step>1?" done":"")} />
          <div className={"stepper-step"+(step===2?" active":"")}>
            <div className="stepper-dot">2</div>
            <span>Review</span>
          </div>
          <div className="stepper-line" />
          <div className="stepper-step">
            <div className="stepper-dot">3</div>
            <span>{financeNow ? "Get paid" : "Send"}</span>
          </div>
        </div>

        {step === 1 && (
          <div className="modal-body">
            <div className="review-section-label">Client</div>
            <div className="ni-field">
              <select className="ni-select" value={buyer} onChange={e=>pickClient(e.target.value)}>
                {CLIENTS.map(c => <option key={c.id} value={c.name}>{c.name} · {c.city}</option>)}
                <option value="__new">+ Add new client…</option>
              </select>
              <span className="ni-caret"><Icon n="caret"/></span>
            </div>

            <div className="review-section-label">Amount & terms</div>
            <div className="ni-grid-2">
              <div className="ni-field">
                <span className="ni-prefix">€</span>
                <input className="ni-input" value={amount} onChange={e=>setAmount(e.target.value)} inputMode="decimal"/>
              </div>
              <div className="ni-field">
                <select className="ni-select" value={terms} onChange={e=>setTerms(e.target.value)}>
                  <option>Net 15</option><option>Net 30</option><option>Net 45</option><option>Net 60</option>
                </select>
                <span className="ni-caret"><Icon n="caret"/></span>
              </div>
            </div>

            <div className="review-section-label">Buyer validation</div>
            <div className="ni-radio-row">
              <label className="ni-radio disabled" title="Not available for this buyer — available after 3+ settled invoices.">
                <input type="radio" name="v" checked={false} disabled readOnly/>
                <div>
                  <b>Auto-validate</b>
                  <span>Unlocks after 3 settled invoices with this buyer.</span>
                </div>
                <span className="ni-radio-lock"><Icon n="lock"/></span>
              </label>
              <label className={"ni-radio"+(validation==="buyer"?" on":"")}>
                <input type="radio" name="v" checked={validation==="buyer"} onChange={()=>setValidation("buyer")}/>
                <div>
                  <b>Buyer confirms</b>
                  <span>Send link; funds release within ~4h of confirmation.</span>
                </div>
              </label>
            </div>

            <div className="review-section-label">Documents</div>
            <div className="ni-docs">
              {docOptions.map(d => (
                <label key={d.id} className={"ni-doc"+(docs.includes(d.id)?" on":"")}>
                  <input type="checkbox" className="cb" checked={docs.includes(d.id)} onChange={()=>toggleDoc(d.id)}/>
                  <Icon n={d.icon}/>
                  <span>{d.label}</span>
                </label>
              ))}
            </div>

            <div className="review-section-label">Internal note</div>
            <textarea className="ni-textarea" value={note} onChange={e=>setNote(e.target.value)} rows={2}/>
          </div>
        )}

        {step === 2 && (
          <div className="modal-body">
            <div className="ni-review-card">
              <div className="ni-review-head">
                <div>
                  <div className="ni-review-id">INV-2026-· draft</div>
                  <div className="ni-review-buyer">{buyer}</div>
                  <div className="ni-review-sub">{buyerSub} · {terms} · Buyer confirmation</div>
                </div>
                <div className="ni-review-amt">
                  <span className="cur">€</span>{amt.toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}
                </div>
              </div>
              <div className="ni-review-docs">
                {docs.map(d => {
                  const meta = (window.DOC_META || {})[d] || { label: d, icon:"file", color:"#475569" };
                  return (
                    <span key={d} className="ni-review-doc">
                      <Icon n={meta.icon} color={meta.color}/>{meta.label}
                    </span>
                  );
                })}
              </div>
              {note && <div className="ni-review-note">“{note}”</div>}
            </div>

            <label className={"ni-finance-toggle"+(financeNow?" on":"")}>
              <div className="ni-ft-left">
                <div className="ni-ft-logo"><Icon n="zap"/></div>
                <div>
                  <div className="ni-ft-title">Get paid now with Aria <span className="ni-ft-chip">Optional</span></div>
                  <div className="ni-ft-sub">Advance this invoice instantly — 2% fee, settles in ~4h.</div>
                </div>
              </div>
              <div className="ni-ft-right">
                <div className="ni-ft-payout">{fmtEur(payout)}</div>
                <div className="ni-ft-payout-sub">net payout</div>
              </div>
              <span className={"ni-switch"+(financeNow?" on":"")} aria-hidden="true"><span className="ni-switch-thumb"/></span>
              <input type="checkbox" className="ni-ft-cb" checked={financeNow} onChange={e=>setFinanceNow(e.target.checked)}/>
            </label>

            {financeNow && (
              <div className="ni-breakdown">
                <div className="ni-bd-row"><span>Invoice amount</span><b>{fmtEur(amt)}</b></div>
                <div className="ni-bd-row minus"><span>Financing fee · 2%</span><b>− {fmtEur(fee)}</b></div>
                <div className="ni-bd-sep"/>
                <div className="ni-bd-row total"><span>You'll receive</span><b>{fmtEur(payout)}</b></div>
                <div className="ni-bd-foot">
                  <Icon n="info"/>
                  <span>A validation link will be sent to {buyer} — funds release within ~4h of their confirmation.</span>
                </div>
              </div>
            )}
          </div>
        )}

        <div className="modal-foot">
          <div className="modal-foot-left">
            {financeNow
              ? <><span style={{color:"#98a2b3"}}>Financing by</span> <img src="aria/logo_forest.png" alt="Aria"/></>
              : <span style={{color:"#cbd5e1"}}>No financing — standard invoice.</span>}
          </div>
          <div className="modal-foot-right">
            {step === 1 && (<>
              <button className="btn btn-secondary" onClick={onClose}>Cancel</button>
              <button className="btn btn-primary" disabled={!valid} onClick={()=>setStep(2)}>
                Continue <Icon n="arrowR"/>
              </button>
            </>)}
            {step === 2 && (<>
              <button className="btn btn-secondary" onClick={()=>setStep(1)}>Back</button>
              <button className="btn btn-primary" onClick={handleCreate}>
                {financeNow
                  ? (<><Icon n="zap" size={14}/> Send & get paid now</>)
                  : (<>Send invoice <Icon n="send"/></>)}
              </button>
            </>)}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { NewInvoiceModal });
