/* ========== Customers ========== */
function CustomersView({ initialCustomerId, onNav }) {
  const state = useStore();
  const [q, setQ] = useState('');
  const [selectedId, setSelectedId] = useState(initialCustomerId || null);
  const [showNew, setShowNew] = useState(false);

  useEffect(() => { if (initialCustomerId) setSelectedId(initialCustomerId); }, [initialCustomerId]);

  // Build customer + aggregates
  const customers = state.customers.map(c => {
    const orders = state.orders.filter(o => o.customerId === c.id);
    const totalSpent = state.income
      .filter(i => orders.some(o => o.id === i.orderId))
      .reduce((s,i)=>s+i.amount, 0);
    return { ...c, orderCount: orders.length, totalSpent };
  });

  const filtered = customers.filter(c => {
    if (!q) return true;
    const t = (c.name + ' ' + (c.phone||'') + ' ' + (c.email||'')).toLowerCase();
    return t.includes(q.toLowerCase());
  });

  if (selectedId) {
    return <CustomerDetail customerId={selectedId} onBack={() => setSelectedId(null)} onNav={onNav}/>;
  }

  return (
    <div>
      <div className="toolbar">
        <div className="search" style={{ flex: 1, maxWidth: 380 }}>
          <Icon name="search" size={14}/>
          <input
            type="text"
            placeholder="Search customers…"
            value={q}
            onChange={e=>setQ(e.target.value)}
            style={{ width: '100%' }}
          />
        </div>
        <div className="spacer"/>
        <button className="btn primary" onClick={() => setShowNew(true)}>
          <Icon name="plus" size={14}/> New customer
        </button>
      </div>

      <div className="card">
        {filtered.length === 0 ? (
          <div className="empty"><h4>No customers</h4><p>Add your first customer to get started.</p></div>
        ) : (
          <table className="tbl">
            <thead>
              <tr>
                <th>Name</th>
                <th>Phone</th>
                <th>Email</th>
                <th className="num">Orders</th>
                <th className="num">Total spent</th>
                <th>Added</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(c => (
                <tr key={c.id} className="clickable" onClick={() => setSelectedId(c.id)}>
                  <td><b>{c.name}</b></td>
                  <td>{c.phone || <span className="dim">—</span>}</td>
                  <td>{c.email || <span className="dim">—</span>}</td>
                  <td className="num">{c.orderCount}</td>
                  <td className="num"><b>{fmtMoney(c.totalSpent, 'USD')}</b></td>
                  <td>{fmtDateShort(c.createdAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {showNew && <CustomerModal onClose={() => setShowNew(false)} onSaved={(id) => { setShowNew(false); setSelectedId(id); }}/>}
    </div>
  );
}

function CustomerDetail({ customerId, onBack, onNav }) {
  const state = useStore();
  const cust = state.customers.find(c => c.id === customerId);
  const [editing, setEditing] = useState(false);

  if (!cust) return <div className="empty"><h4>Customer not found</h4><button className="btn" onClick={onBack}>← Back</button></div>;

  const orders = state.orders.filter(o => o.customerId === cust.id).sort((a,b) => b.createdAt - a.createdAt);
  const invoices = state.invoices.filter(i => i.customerId === cust.id).sort((a,b) => b.date - a.date);
  const totalSpent = state.income.filter(i => orders.some(o => o.id === i.orderId)).reduce((s,i)=>s+i.amount, 0);
  const outstanding = invoices.filter(i => i.status === 'sent').reduce((s,i)=>s+i.total, 0);

  return (
    <div>
      <button className="btn ghost" onClick={onBack} style={{ marginBottom: 14 }}>
        <Icon name="arrowLeft" size={14}/> Back to customers
      </button>

      <div className="detail-head">
        <div className="h-left">
          <h1>{cust.name}</h1>
          <div className="h-meta">
            {cust.phone && <span><Icon name="phone" size={12} style={{verticalAlign: 'middle'}}/> {cust.phone}</span>}
            {cust.email && <><span>·</span><span><Icon name="mail" size={12} style={{verticalAlign: 'middle'}}/> {cust.email}</span></>}
            {cust.address && <><span>·</span><span><Icon name="map" size={12} style={{verticalAlign: 'middle'}}/> {cust.address}</span></>}
          </div>
        </div>
        <div className="hstack">
          <button className="btn" onClick={() => setEditing(true)}><Icon name="edit" size={13}/> Edit</button>
          <button className="btn danger" onClick={() => {
            if (confirm('Delete this customer? Their orders and invoices will remain but unlinked.')) {
              window.PVStore.deleteCustomer(cust.id);
              onBack();
            }
          }}><Icon name="trash" size={13}/></button>
        </div>
      </div>

      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <div className="kpi accent">
          <div className="kpi-label">Orders</div>
          <div className="kpi-value">{orders.length}</div>
        </div>
        <div className="kpi accent-green">
          <div className="kpi-label">Total spent</div>
          <div className="kpi-value">{fmtMoney(totalSpent, 'USD')}</div>
        </div>
        <div className="kpi accent-gold">
          <div className="kpi-label">Outstanding</div>
          <div className="kpi-value">{fmtMoney(outstanding, 'USD')}</div>
        </div>
      </div>

      <div className="split">
        <div className="card">
          <div className="card-header">
            <h3>Order history</h3>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            {orders.length === 0 ? (
              <div className="empty"><p>No orders yet for this customer.</p></div>
            ) : (
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Order</th>
                    <th>Service</th>
                    <th>Stage</th>
                    <th>Created</th>
                    <th className="num">Amount</th>
                  </tr>
                </thead>
                <tbody>
                  {orders.map(o => (
                    <tr key={o.id} className="clickable" onClick={() => onNav('orders', { orderId: o.id })}>
                      <td><span className="order-num">{o.orderNo}</span></td>
                      <td>{countryFlag(o.country)} {o.title}</td>
                      <td><StageBadge stageId={o.stage}/></td>
                      <td>{fmtDateShort(o.createdAt)}</td>
                      <td className="num">{fmtMoney(o.amount, o.currency)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>

        <div className="card">
          <div className="card-header">
            <h3>Invoices</h3>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            {invoices.length === 0 ? (
              <div className="empty"><p>No invoices.</p></div>
            ) : (
              <table className="tbl">
                <thead>
                  <tr>
                    <th>No.</th>
                    <th>Status</th>
                    <th className="num">Total</th>
                  </tr>
                </thead>
                <tbody>
                  {invoices.map(inv => (
                    <tr key={inv.id} className="clickable" onClick={() => onNav('invoices', { invoiceId: inv.id })}>
                      <td><span className="order-num">{inv.no}</span></td>
                      <td><span className={`badge ${inv.status === 'paid' ? 'green' : inv.status === 'sent' ? 'amber' : 'slate'}`}>{inv.status}</span></td>
                      <td className="num"><b>{fmtMoney(inv.total, inv.currency)}</b></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>

      {cust.notes && (
        <div className="card" style={{ marginTop: 16 }}>
          <div className="card-header"><h3>Notes</h3></div>
          <div className="card-body" style={{ whiteSpace: 'pre-wrap', fontSize: 13 }}>{cust.notes}</div>
        </div>
      )}

      {editing && <CustomerModal customer={cust} onClose={() => setEditing(false)} onSaved={() => setEditing(false)}/>}
    </div>
  );
}

function CustomerModal({ customer, onClose, onSaved }) {
  const [form, setForm] = useState({
    name: customer?.name || '',
    phone: customer?.phone || '',
    email: customer?.email || '',
    address: customer?.address || '',
    notes: customer?.notes || '',
  });
  const handleSave = () => {
    if (!form.name.trim()) { alert('Name is required'); return; }
    if (customer) {
      window.PVStore.updateCustomer(customer.id, form);
      onSaved && onSaved(customer.id);
    } else {
      const c = window.PVStore.addCustomer(form);
      onSaved && onSaved(c.id);
    }
  };
  return (
    <Modal
      open
      onClose={onClose}
      title={customer ? 'Edit customer' : 'New customer'}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={handleSave}>{customer ? 'Save' : 'Create'}</button>
      </>}
    >
      <div className="row-gap">
        <div className="field">
          <label>Name</label>
          <input value={form.name} onChange={e=>setForm({...form, name: e.target.value})} placeholder="Full name"/>
        </div>
        <div className="form-row two">
          <div className="field">
            <label>Phone</label>
            <input value={form.phone} onChange={e=>setForm({...form, phone: e.target.value})} placeholder="+856 20 …"/>
          </div>
          <div className="field">
            <label>Email</label>
            <input value={form.email} onChange={e=>setForm({...form, email: e.target.value})}/>
          </div>
        </div>
        <div className="field">
          <label>Address</label>
          <input value={form.address} onChange={e=>setForm({...form, address: e.target.value})}/>
        </div>
        <div className="field">
          <label>Notes</label>
          <textarea value={form.notes} onChange={e=>setForm({...form, notes: e.target.value})} placeholder="Anything to remember about this client…"/>
        </div>
      </div>
    </Modal>
  );
}

window.CustomersView = CustomersView;
window.CustomerModal = CustomerModal;
