// Price Orders — Company-Specific PO Engine (OM Group ERP)
// Manages vendor, customer, and transporter rate agreements per company.
// All logic is data-driven — no hardcoded companies, vendors, customers or materials.
const { useState: poSt, useEffect: poEf, useContext: poCtx, useMemo: poMemo } = React;

const _PTYPES = [
  { value:'vendor',      label:'Vendor',      badgeClass:'bg-bl' },
  { value:'customer',    label:'Customer',    badgeClass:'bg-gn' },
  { value:'transporter', label:'Transporter', badgeClass:'bg-pu' },
];

const _POSH = ({title, action}) => (
  <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:10,paddingBottom:7,borderBottom:'2px solid #FEF3E8'}}>
    <span style={{color:'var(--or)',fontWeight:700,fontSize:13}}>{title}</span>
    {action}
  </div>
);

function PriceOrdersPage() {
  window.useStoreSync();
  const { companyId } = poCtx(window.AppCtx);
  const isGroup = companyId === 'group';

  const [items,   setItems]   = poSt([]);
  const [search,  setSearch]  = poSt('');
  const [fType,   setFType]   = poSt('');
  const [fStatus, setFStatus] = poSt('');
  const [page,    setPage]    = poSt(1);
  const [modal,   setModal]   = poSt(false);
  const [editId,  setEditId]  = poSt(null);
  const [delId,   setDelId]   = poSt(null);
  const [form,    setForm]    = poSt({});
  const [rRows,   setRRows]   = poSt([]);
  const PER = 50;

  poEf(() => { load(); return Store.on(load); }, [companyId]);

  function load() {
    const all = Store.data.priceOrders || [];
    setItems(isGroup ? [...all].reverse() : [...all].filter(p => p.companyId === companyId).reverse());
  }

  function getParties(type, coId) {
    const cid = coId || (isGroup ? 'group' : companyId);
    if (type === 'vendor')      return Store.all('vendors',   cid);
    if (type === 'customer')    return Store.all('customers', cid);
    if (type === 'transporter') return (Store.data.transporterMaster || []);
    return [];
  }

  const mats = Store.all('materials', isGroup ? 'group' : companyId);

  const filtered = poMemo(() => {
    let r = items;
    if (fType)   r = r.filter(p => p.partyType === fType);
    if (fStatus === 'active')   r = r.filter(p =>  p.isActive);
    if (fStatus === 'inactive') r = r.filter(p => !p.isActive);
    if (search) {
      const q = search.toLowerCase();
      r = r.filter(p =>
        (p.poNumber   || '').toLowerCase().includes(q) ||
        (p.partyName  || '').toLowerCase().includes(q) ||
        (p.companyName|| '').toLowerCase().includes(q)
      );
    }
    return r;
  }, [items, fType, fStatus, search]);

  const totalPgs = Math.max(1, Math.ceil(filtered.length / PER));
  const paged    = filtered.slice((page - 1) * PER, page * PER);

  function newRR() { const dg = form.defaultGst; return { id: window.uid(), materialId: '', rate: '', gst: (dg != null && dg !== '') ? dg : '5' }; }
  const setF = (k, v) => setForm(p => ({...p, [k]: v}));

  function openAdd() {
    const coId = isGroup ? '' : companyId;
    setForm({
      companyId:   coId,
      companyName: coId ? Store.name('companies', coId) : '',
      partyType:   'vendor',
      partyId:     '',
      partyName:   '',
      poNumber:    window.RateEngine ? window.RateEngine.genPONumber() : 'PO-' + Date.now(),
      defaultGst:  '5',
      isActive:    false,
      useAcrossAllCompanies: false,
      assignedCompanies: coId ? [coId] : [],
      siteSpecific:    false,
      toCustomerId:    '',
      toCustomerName:  '',
    });
    setRRows([newRR()]);
    setEditId(null); setModal(true);
  }

  function openEdit(po) {
    setForm({
      ...po,
      useAcrossAllCompanies: po.useAcrossAllCompanies || false,
      assignedCompanies: po.assignedCompanies || (po.companyId ? [po.companyId] : []),
    });
    setRRows(po.rates?.length ? po.rates.map(r => ({...r})) : [newRR()]);
    setEditId(po.id); setModal(true);
  }

  function handleParty(pid) {
    const list = getParties(form.partyType, form.companyId);
    const found = list.find(x => x.id === pid);
    setForm(prev => ({...prev, partyId: pid, partyName: found?.name || ''}));
  }

  function handleCompany(coId) {
    setForm(prev => ({...prev, companyId: coId, companyName: Store.name('companies', coId), partyId: '', partyName: ''}));
  }

  function handleSave(e) {
    e.preventDefault();
    if (!form.companyId) { window.toast&&window.toast('Please select a company', 'er'); return; }
    if (!form.partyId)   { window.toast&&window.toast('Please select a party', 'er'); return; }
    if (form.siteSpecific && !form.toCustomerId) { window.toast&&window.toast('Please select a Customer for site-specific rate', 'er'); return; }
    if (!form.poNumber)  { window.toast&&window.toast('PO Number is required', 'er'); return; }
    const valid = rRows.filter(r => r.materialId && r.rate !== '' && parseFloat(r.rate) >= 0);
    if (!valid.length)   { window.toast&&window.toast('Add at least one material rate', 'er'); return; }

    // Always include creator company; empty array when global (no restriction needed)
    const assignedCompanies = form.useAcrossAllCompanies
      ? []
      : [...new Set([...(form.assignedCompanies||[]), form.companyId].filter(Boolean))];
    const record = {
      ...form,
      rates: valid,
      assignedCompanies,
      siteSpecific:   !!form.siteSpecific,
      toCustomerId:   form.siteSpecific ? (form.toCustomerId  || '') : null,
      toCustomerName: form.siteSpecific ? (form.toCustomerName || Store.name('customers', form.toCustomerId) || '') : null,
    };

    if (editId) {
      Store.update('priceOrders', editId, record);
      if (form.isActive && window.RateEngine) window.RateEngine.activatePO(editId);
      Store.addLog('UPDATE', 'Price Order', `Updated PO ${form.poNumber} — ${form.partyName} [${form.companyName}]`);
    } else {
      const np = Store.add('priceOrders', record);
      if (form.isActive && window.RateEngine) window.RateEngine.activatePO(np.id);
      Store.addLog('CREATE', 'Price Order', `Created PO ${form.poNumber} — ${form.partyName} [${form.companyName}]`);
    }

    setModal(false); load();
    window.toast&&window.toast('Price Order saved', 'ok');
  }

  function handleDelete() {
    const po = Store.byId('priceOrders', delId);
    if (po && window.RateEngine) window.RateEngine.onPODeleted(po);
    Store.del('priceOrders', delId);
    Store.addLog('DELETE', 'Price Order', `Deleted ${po?.poNumber || delId}`);
    setDelId(null); load();
    window.toast&&window.toast('Deleted', 'ok');
  }

  function toggleActive(po) {
    if (!window.RateEngine) return;
    if (po.isActive) {
      window.RateEngine.deactivatePO(po.id);
      window.toast&&window.toast('PO Deactivated', 'ok');
    } else {
      window.RateEngine.activatePO(po.id);
      window.toast&&window.toast('PO set as Active', 'ok');
    }
    load();
  }

  const allCos = Store.all('companies');

  // Active PO lookup for the currently selected company + party (for preview)
  const existingActivePO = poMemo(() => {
    if (!form.companyId || !form.partyType || !form.partyId || !editId) return null;
    const all = Store.data.priceOrders || [];
    return all.find(p =>
      p.id        !== editId         &&
      p.companyId === form.companyId &&
      p.partyType === form.partyType &&
      p.partyId   === form.partyId   &&
      p.isActive  === true           &&
      // Match same tier: general vs site-specific (same customer)
      (form.siteSpecific
        ? (p.siteSpecific === true && p.toCustomerId === form.toCustomerId)
        : !p.siteSpecific)
    ) || null;
  }, [form.companyId, form.partyType, form.partyId, form.siteSpecific, form.toCustomerId, editId, items]);

  return (
    <div>
      {/* Header */}
      <div className="ph">
        <div>
          <h1>Price Orders</h1>
          <p>Company-specific rate agreements — vendors, customers &amp; transporters</p>
        </div>
        <div className="ph-act">
          <button className="btn btn-wh btn-sm" onClick={()=>{
            const hdr=['PO Number','Company','Party Type','Party Name','Material Rates','Default GST%','Status','Effective Date'];
            const rows=filtered.map(po=>[
              po.poNumber||'',
              po.companyName||Store.name('companies',po.companyId)||'',
              po.partyType||'',
              po.partyName||'',
              (po.rates||[]).map(r=>(Store.name('materials',r.materialId)||r.materialId||'')+': ₹'+r.rate).join(' | '),
              (po.defaultGst||5)+'%',
              po.isActive?'Active':'Inactive',
              po.effectiveDate||'',
            ].map(v=>'"'+String(v).replace(/"/g,'""')+'"'));
            const csv='\uFEFF'+[hdr.map(h=>'"'+h+'"').join(','),...rows.map(r=>r.join(','))].join('\r\n');
            const blob=new Blob([csv],{type:'text/csv;charset=utf-8'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='price_orders.csv';document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1500);
            window.toast&&window.toast('Exported '+filtered.length+' price orders','ok');
          }}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> Export CSV</button>
          <button className="btn btn-or" onClick={openAdd}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> New Price Order</button>
        </div>
      </div>

      {/* Filters */}
      <div className="frow">
        <div className="fs">
          <svg className="fs-ic" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={e => {setSearch(e.target.value); setPage(1);}} placeholder="Search PO number, party name, company…"/>
        </div>
        <window.FiltSelect placeholder="All Party Types" value={fType} onChange={v => {setFType(v); setPage(1);}} options={_PTYPES.map(t => ({value:t.value,label:t.label}))}/>
        <window.FiltSelect placeholder="All Status" value={fStatus} onChange={v => {setFStatus(v); setPage(1);}} options={[{value:'active',label:'Active'},{value:'inactive',label:'Inactive'}]}/>
        {(search || fType || fStatus) && (
          <button className="btn btn-gh btn-sm" onClick={() => {setSearch(''); setFType(''); setFStatus(''); setPage(1);}}>Clear</button>
        )}
        <span className="f-cnt">{filtered.length} price orders</span>
      </div>

      {/* Table */}
      <div className="card">
        <div className="tbl-w">
          <table className="tbl">
            <thead>
              <tr>
                <th>PO NUMBER</th>
                <th>COMPANY</th>
                <th>PARTY TYPE</th>
                <th>PARTY NAME</th>
                <th>MATERIAL RATES</th>
                <th>DEFAULT GST</th>
                <th>STATUS</th>
                <th>ACTIONS</th>
              </tr>
            </thead>
            <tbody>
              {paged.length === 0
                ? <tr className="empty"><td colSpan="8" style={{textAlign:'center',padding:44,color:'var(--txt2)'}}>
                    No price orders found. Click <strong>+ New Price Order</strong> to create one.
                  </td></tr>
                : paged.map(po => {
                    const pt = _PTYPES.find(t => t.value === po.partyType) || _PTYPES[0];
                    const preview = (po.rates || []).slice(0, 3)
                      .map(r => `${Store.name('materials', r.materialId)}: ₹${r.rate}`)
                      .join(' · ');
                    return (
                      <tr key={po.id}>
                        <td>
                          <span style={{fontFamily:'var(--font)',fontSize:11.5,fontWeight:700,color:'var(--or)'}}>{po.poNumber}</span>
                          {po.effectiveDate && <div style={{fontSize:10,color:'var(--txt3)',marginTop:1}}>Eff: {window.fmtDate(po.effectiveDate)}</div>}
                        </td>
                        <td>
                          <span className="bdg bg-or" style={{fontSize:10}}>{po.companyName || Store.name('companies', po.companyId)}</span>
                          {po.useAcrossAllCompanies
                            ? <div style={{fontSize:10,color:'#16a34a',marginTop:3,fontWeight:600,display:'flex',alignItems:'center',gap:4}}><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>All Companies</div>
                            : po.assignedCompanies && po.assignedCompanies.length > 1
                              ? <div style={{fontSize:10,color:'var(--txt3)',marginTop:3}}>{po.assignedCompanies.length} companies</div>
                              : null}
                        </td>
                        <td><span className={`bdg ${pt.badgeClass}`} style={{fontSize:10,textTransform:'capitalize'}}>{pt.label}</span></td>
                        <td style={{fontWeight:500}}>
                          {po.partyName}
                          {po.siteSpecific && po.toCustomerName && (
                            <div style={{fontSize:10,color:'var(--info)',marginTop:2,display:'flex',alignItems:'center',gap:3,fontWeight:600}}>
                              <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                              {po.toCustomerName}
                            </div>
                          )}
                        </td>
                        <td style={{fontSize:11,color:'var(--txt2)',maxWidth:220,whiteSpace:'normal',lineHeight:1.6}}>
                          {preview || '—'}
                          {(po.rates || []).length > 3 && <span style={{color:'var(--txt3)'}}> +{(po.rates||[]).length - 3} more</span>}
                        </td>
                        <td style={{color:'var(--txt2)'}}>{po.defaultGst || 5}%</td>
                        <td>
                          {po.isActive
                            ? <span className="bdg bg-gn" style={{fontSize:11}}>● Active</span>
                            : <span className="bdg bg-gy" style={{fontSize:11}}>Inactive</span>}
                        </td>
                        <td>
                          <div className="ra">
                            <button
                              className={`btn btn-sm ${po.isActive ? 'btn-wh' : 'btn-gn'}`}
                              style={{fontSize:10.5}}
                              onClick={() => toggleActive(po)}
                            >
                              {po.isActive ? 'Deactivate' : 'Set Active'}
                            </button>
                            <button className="btn btn-wh btn-sm" onClick={() => openEdit(po)}>Edit</button>
                            <button className="btn btn-rd btn-sm" onClick={() => setDelId(po.id)}>Delete</button>
                          </div>
                        </td>
                      </tr>
                    );
                  })
              }
            </tbody>
          </table>
        </div>
      </div>

      {totalPgs > 1 && (
        <div className="pag">
          <button className="pg-b" onClick={() => setPage(1)} disabled={page===1}>«</button>
          <button className="pg-b" onClick={() => setPage(p => p-1)} disabled={page===1}>‹</button>
          <span className="pg-inf">Page {page} of {totalPgs}</span>
          <button className="pg-b" onClick={() => setPage(p => p+1)} disabled={page===totalPgs}>›</button>
          <button className="pg-b" onClick={() => setPage(totalPgs)} disabled={page===totalPgs}>»</button>
        </div>
      )}

      {/* Add / Edit Modal */}
      {modal && (
        <div className="mbg">
          <div className="mod mod-xl" style={{maxHeight:'92vh'}}>
            <div className="mod-hd">
              <h2>{editId ? 'Edit' : 'New'} Price Order</h2>
              <button className="mod-x" onClick={() => setModal(false)}>×</button>
            </div>
            <form onSubmit={handleSave}>
              <div className="mod-bd">
                <_POSH title="Price Order Details"/>

                {/* Row 1: Company, Party Type, Party Name */}
                <div className="fg3" style={{marginBottom:12}}>
                  <div className="fld">
                    <label>Company <span className="req">*</span></label>
                    {isGroup
                      ? <window.FormSelect placeholder="Select Company" value={form.companyId||''} onChange={v => handleCompany(v)} options={allCos.map(c => ({value:c.id,label:c.name}))}/>
                      : <input className="inp" value={form.companyName || Store.name('companies', companyId)} readOnly style={{background:'#F9FAFB',color:'var(--txt2)'}}/>
                    }
                  </div>
                  <div className="fld">
                    <label>Party Type <span className="req">*</span></label>
                    <window.FormSelect value={form.partyType||'vendor'}
                      onChange={v => setForm(p => ({...p, partyType: v, partyId: '', partyName: ''}))} options={_PTYPES.map(t => ({value:t.value,label:t.label}))}/>
                  </div>
                  <div className="fld">
                    <label>{_PTYPES.find(t => t.value === form.partyType)?.label || 'Party'} Name <span className="req">*</span></label>
                    <window.FormSelect placeholder={'Select '+(form.partyType || 'party')+'…'} value={form.partyId||''} onChange={v => handleParty(v)} options={getParties(form.partyType || 'vendor', form.companyId).map(p => ({value:p.id,label:p.name}))}/>
                  </div>
                </div>

                {/* Site-Specific Rate (vendor POs only) */}
                {form.partyType === 'vendor' && (
                  <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:4,padding:'11px 14px',marginBottom:12}}>
                    <label style={{display:'flex',alignItems:'flex-start',gap:9,cursor:'pointer'}}>
                      <input type="checkbox" checked={!!form.siteSpecific}
                        onChange={e => setForm(p => ({...p, siteSpecific: e.target.checked, toCustomerId: '', toCustomerName: ''}))}
                        style={{accentColor:'var(--or)',marginTop:3,width:14,height:14,flexShrink:0}}/>
                      <span>
                        <span style={{fontSize:12.5,fontWeight:600}}>Enable Customer / Site Specific Rate</span>
                        <span style={{display:'block',fontSize:11,color:'var(--txt2)',marginTop:3,lineHeight:1.55}}>
                          This PO applies to a specific customer/site only. The same vendor can have different rates for different customers. Falls back to a general PO if no customer-specific one is found.
                        </span>
                      </span>
                    </label>
                    {form.siteSpecific && (
                      <div style={{marginTop:11,paddingTop:10,borderTop:'1px solid var(--bdr)'}}>
                        <div className="fld" style={{maxWidth:320}}>
                          <label>To Customer <span className="req">*</span></label>
                          <window.FormSelect placeholder="Select Customer / Site…" value={form.toCustomerId||''}
                            onChange={v => {
                              const found = getParties('customer', form.companyId).find(c => c.id === v);
                              setForm(p => ({...p, toCustomerId: v, toCustomerName: found?.name||''}));
                            }}
                            options={getParties('customer', form.companyId).map(c => ({value:c.id,label:c.name}))}/>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Row 2: PO Number, Default GST, Effective Date */}
                <div className="fg3" style={{marginBottom:14}}>
                  <div className="fld">
                    <label>PO Number <span className="req">*</span></label>
                    <input className="inp" value={form.poNumber||''} onChange={e => setF('poNumber', e.target.value)} required placeholder="PO-06212026-01"/>
                  </div>
                  <div className="fld">
                    <label>Default GST %</label>
                    <window.FormSelect value={form.defaultGst||'5'} onChange={v => setF('defaultGst', v)} options={[{value:'0',label:'0% Exempt'},{value:'5',label:'5%'},{value:'12',label:'12%'},{value:'18',label:'18%'},{value:'28',label:'28%'}]}/>
                  </div>
                  <div className="fld">
                    <label>Effective Date</label>
                    <input className="inp" type="date" value={form.effectiveDate||''} onChange={e => setF('effectiveDate', e.target.value)}/>
                  </div>
                </div>

                {/* Active PO checkbox */}
                <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:4,padding:'11px 14px',marginBottom:16}}>
                  <label style={{display:'flex',alignItems:'flex-start',gap:9,cursor:'pointer'}}>
                    <input type="checkbox" checked={!!form.isActive} onChange={e => setF('isActive', e.target.checked)} style={{accentColor:'var(--or)',marginTop:3,width:14,height:14,flexShrink:0}}/>
                    <span>
                      <span style={{fontSize:12.5,fontWeight:600}}>Set as Active Price Order</span>
                      <span style={{display:'block',fontSize:11,color:'var(--txt2)',marginTop:4,lineHeight:1.55}}>
                        This will automatically deactivate other active price orders for this {form.partyType||'party'} within the currently selected company only.
                        Active price orders become the default rate source for all future transactions.
                      </span>
                      {form.isActive && existingActivePO && (
                        <span style={{display:'block',fontSize:11,color:'var(--warn)',marginTop:4,fontWeight:500}}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{display:'inline',verticalAlign:'-1px',flexShrink:0,marginRight:4}}><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>Currently active: <strong>{existingActivePO.poNumber}</strong> — it will be deactivated when you save.
                        </span>
                      )}
                    </span>
                  </label>
                </div>

                {/* Rate Availability */}
                <div style={{background:'#F9FAFB',border:'1px solid var(--bdr)',borderRadius:4,padding:'11px 14px',marginBottom:16}}>
                  <div style={{fontWeight:700,fontSize:13,color:'var(--or)',marginBottom:10,paddingBottom:7,borderBottom:'2px solid #FEF3E8'}}>Rate Availability</div>
                  <label style={{display:'flex',alignItems:'flex-start',gap:9,cursor:'pointer',marginBottom:form.useAcrossAllCompanies?0:12}}>
                    <input type="checkbox" checked={!!form.useAcrossAllCompanies}
                      onChange={e => setF('useAcrossAllCompanies', e.target.checked)}
                      style={{accentColor:'var(--or)',marginTop:3,width:14,height:14,flexShrink:0}}/>
                    <span>
                      <span style={{fontSize:12.5,fontWeight:600}}>Use Across All Companies</span>
                      <span style={{display:'block',fontSize:11,color:'var(--txt2)',marginTop:3,lineHeight:1.55}}>
                        This PO becomes available to every company in the group. New companies added later automatically inherit access.
                      </span>
                    </span>
                  </label>
                  {!form.useAcrossAllCompanies && (
                    <div>
                      <div style={{fontSize:11.5,fontWeight:600,color:'var(--txt1)',marginBottom:7}}>Assign To Companies</div>
                      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(190px,1fr))',gap:'4px 12px'}}>
                        {allCos.map(co => {
                          const isCreator = co.id === form.companyId;
                          const checked   = isCreator || (form.assignedCompanies||[]).includes(co.id);
                          return (
                            <label key={co.id} style={{display:'flex',alignItems:'center',gap:7,cursor:isCreator?'default':'pointer',padding:'3px 0',fontSize:12}}>
                              <input type="checkbox"
                                checked={checked}
                                disabled={isCreator}
                                onChange={e => {
                                  const cur = (form.assignedCompanies||[]).filter(id => id !== co.id);
                                  setF('assignedCompanies', e.target.checked ? [...cur, co.id] : cur);
                                }}
                                style={{accentColor:'var(--or)',width:13,height:13,flexShrink:0}}/>
                              <span style={{color:isCreator?'var(--txt2)':'var(--txt1)'}}>{co.name}</span>
                              {isCreator && <span style={{fontSize:10,color:'var(--txt3)',marginLeft:2}}>(creator)</span>}
                            </label>
                          );
                        })}
                        {allCos.length === 0 && <div style={{fontSize:11,color:'var(--txt3)',fontStyle:'italic'}}>No companies found.</div>}
                      </div>
                    </div>
                  )}
                </div>

                {/* Material-wise Rates */}
                <_POSH title="Material-Wise Rates" action={
                  <button type="button" className="btn btn-or btn-sm" onClick={() => setRRows(p => [...p, newRR()])}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Add Material
                  </button>
                }/>

                {rRows.length === 0
                  ? <div style={{fontSize:12,color:'var(--txt3)',fontStyle:'italic',padding:'6px 0 4px'}}>
                      No rates added. Click "+ Add Material" to define material-wise rates for this PO.
                    </div>
                  : <div className="ig">
                      <table>
                        <thead>
                          <tr>
                            <th style={{minWidth:160}}>Material <span className="req">*</span></th>
                            <th style={{minWidth:110}}>Rate (₹ / Ton) <span className="req">*</span></th>
                            <th style={{minWidth:90}}>GST %</th>
                            <th style={{width:32}}></th>
                          </tr>
                        </thead>
                        <tbody>
                          {rRows.map((row, idx) => (
                            <tr key={row.id}>
                              <td>
                                <select value={row.materialId}
                                  onChange={e => setRRows(p => p.map((r,i) => i===idx ? {...r, materialId: e.target.value} : r))}
                                  style={{width:'100%'}}>
                                  <option value="">Select Material</option>
                                  {mats.map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
                                </select>
                              </td>
                              <td>
                                <input type="number" value={row.rate}
                                  onChange={e => setRRows(p => p.map((r,i) => i===idx ? {...r, rate: e.target.value} : r))}
                                  style={{width:100}} min="0" step="0.01" placeholder="0.00"/>
                              </td>
                              <td>
                                <select value={row.gst || form.defaultGst || '5'}
                                  onChange={e => setRRows(p => p.map((r,i) => i===idx ? {...r, gst: e.target.value} : r))}
                                  style={{width:90}}>
                                  <option value="0">0% Exempt</option>
                                  <option value="5">5%</option>
                                  <option value="12">12%</option>
                                  <option value="18">18%</option>
                                  <option value="28">28%</option>
                                </select>
                              </td>
                              <td>
                                {rRows.length > 1 && (
                                  <button type="button"
                                    onClick={() => setRRows(p => p.filter((_,i) => i !== idx))}
                                    style={{background:'none',border:'none',color:'var(--err)',cursor:'pointer',fontSize:18,padding:'0 4px',lineHeight:1}}>
                                    ×
                                  </button>
                                )}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                }

                {/* PO Summary */}
                {form.companyName && form.partyName && rRows.some(r => r.materialId && r.rate !== '') && (
                  <div style={{marginTop:14,background:'#FFFBF5',border:'1px solid var(--or-bdr)',borderRadius:4,padding:'10px 14px'}}>
                    <div style={{fontWeight:700,fontSize:12,color:'var(--or)',marginBottom:6}}>PO Summary</div>
                    <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'4px 16px',fontSize:11.5,color:'var(--txt2)',lineHeight:1.7}}>
                      <div><strong>Company:</strong> {form.companyName}</div>
                      <div><strong>PO Number:</strong> <span style={{fontFamily:'var(--font)'}}>{form.poNumber}</span></div>
                      <div><strong>Party:</strong> {form.partyName}</div>
                      <div><strong>Party Type:</strong> <span style={{textTransform:'capitalize'}}>{form.partyType}</span></div>
                      <div><strong>Rates Defined:</strong> {rRows.filter(r => r.materialId && r.rate !== '').length} material(s)</div>
                      <div><strong>Status:</strong> {form.isActive ? '● Active' : 'Inactive'}</div>
                      <div><strong>Availability:</strong> {form.useAcrossAllCompanies ? 'All Companies' : `${(form.assignedCompanies||[]).length} company(s)`}</div>
                    </div>
                  </div>
                )}
              </div>
              <div className="mod-ft">
                <button type="button" className="btn btn-wh" onClick={() => setModal(false)}>Cancel</button>
                <button type="submit" className="btn btn-or">{editId ? 'Update Price Order' : 'Create Price Order'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {delId && <window.Confirm onOk={handleDelete} onCancel={() => setDelId(null)}/>}
    </div>
  );
}

window.PriceOrdersPage = PriceOrdersPage;
