// views-ops.jsx — Services & Pricing, Purchasing, Finances, Team, simple stubs.
const { useState: useSo, useEffect: useOpsEffect } = React;

/* ====================== SERVICES & PRICING ====================== */
function ServiceModal({ service, onClose, onSave }) {
  const [draft, setDraft] = useSo(() => service ? { ...service } : {
    id: '',
    name: '',
    cat: 'Maintenance',
    spec: 'Mechanics',
    net: 0,
    dur: '1 h',
    active: true,
  });
  const valid = draft.name.trim().length > 2 && Number(draft.net) > 0 && draft.dur.trim();
  return (
    <Modal title={service ? tx('Edit service') : tx('Add service')} sub={tx('Service becomes visible in the marketplace when active')} onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Cancel')}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={() => onSave({ ...draft, name: draft.name.trim(), net: Number(draft.net), dur: draft.dur.trim() })}>
          {React.createElement(Icon.check, { size: 15, stroke: 2.6 })} {tx('Save service')}
        </button>
      </>}>
      <div className="field">
        <label>{tx('Service')}</label>
        <input className="input" value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} placeholder={tx('e.g. Oil & filter change')} autoFocus />
      </div>
      <div className="grid-2">
        <div className="field">
          <label>{tx('Category')}</label>
          <select className="select" value={draft.cat} onChange={(e) => setDraft({ ...draft, cat: e.target.value })}>
            {['Maintenance', 'Brakes', 'Chassis', 'Climate', 'Diagnostics', 'Paint', 'Electrical', 'Engine'].map((x) => <option key={x} value={x}>{tx(x)}</option>)}
          </select>
        </div>
        <div className="field">
          <label>{tx('Specialization')}</label>
          <select className="select" value={draft.spec} onChange={(e) => setDraft({ ...draft, spec: e.target.value })}>
            {SHOP.specializations.map((x) => <option key={x} value={x}>{tx(x)}</option>)}
          </select>
        </div>
      </div>
      <div className="grid-2">
        <div className="field">
          <label>{tx('Net (you)')}</label>
          <div className="input-money">
            <span>zł</span>
            <input className="input" type="number" min="1" value={draft.net || ''} onChange={(e) => setDraft({ ...draft, net: e.target.value })} />
          </div>
          {Number(draft.net) > 0 && <div className="hint">{tx('Client “from”')}: <b className="mono">{zl(displayed(Number(draft.net)))}</b></div>}
        </div>
        <div className="field">
          <label>{tx('Duration')}</label>
          <input className="input" value={draft.dur} onChange={(e) => setDraft({ ...draft, dur: e.target.value })} />
        </div>
      </div>
      <div className="cap" style={{ padding: '8px 0 0' }}>
        <div className={`cap-ic ${draft.active ? 'on' : ''}`}>{React.createElement(Icon.tag, { size: 18 })}</div>
        <div className="cap-main">
          <div className="between">
            <div><div className="cap-title">{tx('Active')}</div><div className="cap-sub">{tx('Active services are bookable by clients')}</div></div>
            <Switch on={draft.active} onClick={() => setDraft({ ...draft, active: !draft.active })} />
          </div>
        </div>
      </div>
    </Modal>
  );
}

function PricingView() {
  const [list, setList] = useStoredState('ac.services', SERVICES);
  const [editing, setEditing] = useSo(null);
  const [deleting, setDeleting] = useSo(null);
  const [query, setQuery] = useSo('');
  const [status, setStatus] = useSo('all');
  const toggle = (id) => setList((l) => l.map((s) => s.id === id ? { ...s, active: !s.active } : s));
  const filtered = list.filter((s) => {
    const hay = `${s.name} ${s.cat} ${s.spec} ${s.dur}`.toLowerCase();
    const matchesText = !query.trim() || hay.includes(query.trim().toLowerCase());
    const matchesStatus = status === 'all' || (status === 'active' ? s.active : !s.active);
    return matchesText && matchesStatus;
  });
  const save = async (service) => {
    const apiService = await AutoCareAPI.saveService(service).catch((e) => (console.warn('[AutoCareAPI] service save failed', e), null));
    const nextService = apiService || service;
    if (service.id) {
      setList((l) => l.map((s) => s.id === service.id ? nextService : s));
      toast(apiService ? tx('Service updated in backend') : tx('Service updated'), 'check');
    } else {
      const id = 's' + (Math.max(...list.map((s) => Number(String(s.id).replace('s', '')) || 0)) + 1);
      setList((l) => [{ ...nextService, id: nextService.id || id }, ...l]);
      toast(apiService ? tx('Service published in backend') : tx('Service added and published'), 'tag');
    }
    setEditing(null);
  };
  const remove = async () => {
    if (!deleting) return;
    await AutoCareAPI.setServiceActive(deleting, false).catch((e) => console.warn('[AutoCareAPI] service delete failed', e));
    setList((l) => l.filter((s) => s.id !== deleting.id));
    toast(tx('Service deleted from catalogue'), 'trash');
    setDeleting(null);
  };
  return (
    <div className="page view-fade" data-screen-label="Pricing">
      <div className="page-head">
        <div><div className="page-title">{tx('Services & pricing')}</div><div className="page-sub">{fmt('Net prices you set · clients see the “from” price incl. {n}% platform fee', { n: Math.round(TAKE_RATE * 100) })}</div></div>
        <span className="spacer" />
        <div className="input" style={{ width: 260, display: 'flex', alignItems: 'center', gap: 8 }}>
          {React.createElement(Icon.search, { size: 15, style: { color: 'var(--text-3)' } })}
          <input style={{ border: 0, outline: 0, background: 'transparent', flex: 1, minWidth: 0, font: 'inherit', color: 'var(--text)' }} value={query} onChange={(e) => setQuery(e.target.value)} placeholder={tx('Search services')} />
        </div>
        <button className="btn btn-primary" onClick={() => setEditing({})}>{React.createElement(Icon.plus, { size: 15, stroke: 2.6 })} {tx('Add service')}</button>
      </div>

      <div className="grid-3" style={{ marginBottom: 18 }}>
        <Stat label={tx('Active services')} icon="tag" value={String(list.filter((s) => s.active).length)} />
        <Stat label={tx('Platform take rate')} icon="trend" value={`${Math.round(TAKE_RATE * 100)}%`} delta={tx('global default')} deltaDir="flat" />
        <Stat label={tx('Avg. client price')} icon="wallet" value={zl(Math.round(list.reduce((a, s) => a + displayed(s.net), 0) / list.length))} deltaDir="flat" />
      </div>

      <div className="card">
        <div className="card-hd">
          <h3>{tx('Catalogue')}</h3>
          <span className="spacer" />
          <div className="seg">
            {['all', 'active', 'inactive'].map((x) => <button key={x} className={status === x ? 'on' : ''} onClick={() => setStatus(x)}>{tx(x[0].toUpperCase() + x.slice(1))}</button>)}
          </div>
        </div>
        <table className="tbl">
          <thead><tr>
            <th>{tx('Service')}</th><th>{tx('Category')}</th><th>{tx('Specialization')}</th><th>{tx('Duration')}</th>
            <th style={{ textAlign: 'right' }}>{tx('Net (you)')}</th><th style={{ textAlign: 'right' }}>{tx('Client “from”')}</th><th style={{ textAlign: 'right' }}>{tx('Fee')}</th><th>{tx('Active')}</th><th></th>
          </tr></thead>
          <tbody>
            {filtered.map((s) => (
              <tr key={s.id}>
                <td className="strong">{tx(s.name)}</td>
                <td><Badge kind="outline">{tx(s.cat)}</Badge></td>
                <td className="muted">{tx(s.spec)}</td>
                <td className="muted">{tx(s.dur)}</td>
                <td className="num">{zl(s.net)}</td>
                <td className="num strong" style={{ color: 'var(--text)' }}>{zl(displayed(s.net))}</td>
                <td className="num muted">{zl(fee(s.net))}</td>
                <td><Switch on={s.active} onClick={async () => {
                  const next = await AutoCareAPI.setServiceActive(s, !s.active).catch((e) => (console.warn('[AutoCareAPI] service active failed', e), null));
                  if (next) setList((l) => l.map((item) => item.id === s.id ? next : item));
                  else toggle(s.id);
                  toast(s.active ? tx('Service deactivated') : tx('Service activated'), 'tag');
                }} /></td>
                <td>
                  <div className="row" style={{ justifyContent: 'flex-end', gap: 6 }}>
                    <button className="icon-btn" title={tx('Edit')} style={{ width: 28, height: 28 }} onClick={() => setEditing(s)}>{React.createElement(Icon.edit, { size: 14 })}</button>
                    <button className="icon-btn" title={tx('Delete')} style={{ width: 28, height: 28, color: 'var(--danger)' }} onClick={() => setDeleting(s)}>{React.createElement(Icon.trash, { size: 14 })}</button>
                  </div>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && <tr><td colSpan="9" className="muted">{tx('No services match this filter')}</td></tr>}
          </tbody>
        </table>
      </div>
      {editing && <ServiceModal service={editing.id ? editing : null} onClose={() => setEditing(null)} onSave={save} />}
      {deleting && (
        <Modal title={tx('Delete service')} sub={deleting.name} onClose={() => setDeleting(null)}
          footer={<>
            <button className="btn btn-ghost" onClick={() => setDeleting(null)}>{tx('Cancel')}</button>
            <button className="btn btn-danger" onClick={remove}>{React.createElement(Icon.trash, { size: 15 })} {tx('Delete')}</button>
          </>}>
          <div className="card" style={{ background: 'var(--danger-soft)', color: 'var(--danger)', boxShadow: 'none', border: 'none', padding: '12px 14px', lineHeight: 1.5 }}>
            {tx('This removes the service from the bookable catalogue. Existing work orders keep their original line items.')}
          </div>
        </Modal>
      )}
    </div>
  );
}

/* ========================== PURCHASING ========================== */
function SupplyRow({ s, onAdvance }) {
  const next = s.status === 'open' || s.status === 'overdue' ? 'ordered' : s.status === 'ordered' ? 'closed' : null;
  const badge = { open: 'warning', ordered: 'accent', closed: 'neutral', overdue: 'danger' }[s.status];
  const label = { open: 'Open', ordered: 'Ordered', closed: 'Closed', overdue: 'Overdue' }[s.status];
  return (
    <tr>
      <td><div className="strong sec">{tx(s.item)}</div><div className="tiny muted">{s.id} · {tx(s.qty)}</div></td>
      <td><div className="row" style={{ gap: 8 }}><Avatar name={teamById(s.author)?.name} size={24} /><span className="tiny">{teamById(s.author)?.name.split(' ')[0]}<div className="muted">{tx(teamById(s.author)?.role)}</div></span></div></td>
      <td>{s.wo ? <span className="mono tiny muted2">{s.wo}</span> : <span className="muted tiny">{tx('standalone')}</span>}</td>
      <td>{s.priority === 'high' ? <Badge kind="danger">{tx('High')}</Badge> : s.priority === 'low' ? <Badge kind="neutral">{tx('Low')}</Badge> : <Badge kind="outline">{tx('Normal')}</Badge>}</td>
      <td><span className={s.status === 'overdue' ? '' : 'muted2'} style={s.status === 'overdue' ? { color: 'var(--danger)', fontWeight: 600 } : null}>{tdate(s.deadline)}</span></td>
      <td><Badge kind={badge} pip>{tx(label)}</Badge>{s.note && <div className="tiny muted" style={{ marginTop: 3, maxWidth: 200 }}>{tx(s.note)}</div>}</td>
      <td style={{ textAlign: 'right' }}>
        {next && <button className="btn btn-outline sm" onClick={() => onAdvance(s.id, next)}>
          {next === 'ordered' ? tx('Mark ordered') : tx('Close')}
        </button>}
      </td>
    </tr>
  );
}

function PurchasingView() {
  const [list, setList] = useStoredState('ac.supply', SUPPLY);
  const [showNew, setShowNew] = useSo(false);
  const [showParts, setShowParts] = useSo(false);
  const [sort, setSort] = useSo('deadline');
  const advance = async (id, status) => {
    const current = list.find((s) => s.id === id);
    const apiItem = current ? await AutoCareAPI.advanceSupplyRequest(current, status).catch((e) => (console.warn('[AutoCareAPI] supply advance failed', e), null)) : null;
    setList((l) => l.map((s) => s.id === id ? (apiItem || { ...s, status }) : s));
    toast(status === 'ordered' ? tx('Marked as ordered — author notified') : tx('Request closed — author notified'), status === 'ordered' ? 'cart' : 'check');
  };
  const createRequest = async (draft) => {
    const apiItem = await AutoCareAPI.createSupplyRequest(draft).catch((e) => (console.warn('[AutoCareAPI] supply create failed', e), null));
    const id = 'SR-' + (300 + list.length + 1);
    setList((l) => [apiItem || { id, author: 'u1', wo: draft.wo || null, status: 'open', note: '', ...draft }, ...l]);
    setShowNew(false);
    toast(apiItem ? tx('Supply request created in backend') : tx('Supply request created'), 'cart');
  };
  const rows = [...list].sort((a, b) => {
    if (sort === 'author') return (teamById(a.author)?.name || '').localeCompare(teamById(b.author)?.name || '');
    if (sort === 'order') return String(a.wo || '').localeCompare(String(b.wo || ''));
    const rank = { overdue: 0, open: 1, ordered: 2, closed: 3 };
    return (rank[a.status] ?? 9) - (rank[b.status] ?? 9);
  });
  const open = list.filter((s) => ['open', 'overdue'].includes(s.status)).length;
  return (
    <div className="page view-fade" data-screen-label="Purchasing">
      <div className="page-head">
        <div><div className="page-title">{tx('Purchasing')}</div><div className="page-sub">{tx('Supply requests from the floor — order, then close to notify the author')}</div></div>
        <span className="spacer" />
        <button className="btn btn-outline" onClick={() => setShowParts(true)}>{React.createElement(Icon.package, { size: 15 })} {tx('Part orders')}</button>
        <button className="btn btn-primary" onClick={() => setShowNew(true)}>{React.createElement(Icon.plus, { size: 15, stroke: 2.6 })} {tx('New request')}</button>
      </div>

      <div className="grid-3" style={{ marginBottom: 18 }}>
        <Stat label={tx('Open requests')} icon="list" value={String(open)} accent />
        <Stat label={tx('Overdue')} icon="alert" value={String(list.filter((s) => s.status === 'overdue').length)} delta={tx('needs attention')} deltaDir="flat" />
        <Stat label={tx('Closed this week')} icon="check" value="11" delta={tx('on time 91%')} />
      </div>

      <div className="card">
        <div className="card-hd"><h3>{tx('Shopping list')}</h3><span className="spacer" /><div className="seg">
          <button className={sort === 'deadline' ? 'on' : ''} onClick={() => setSort('deadline')}>{tx('By deadline')}</button>
          <button className={sort === 'order' ? 'on' : ''} onClick={() => setSort('order')}>{tx('By order')}</button>
          <button className={sort === 'author' ? 'on' : ''} onClick={() => setSort('author')}>{tx('By author')}</button>
        </div></div>
        <table className="tbl">
          <thead><tr><th>{tx('Item')}</th><th>{tx('Requested by')}</th><th>{tx('Order')}</th><th>{tx('Priority')}</th><th>{tx('Deadline')}</th><th>{tx('Status')}</th><th></th></tr></thead>
          <tbody>{rows.map((s) => <SupplyRow key={s.id} s={s} onAdvance={advance} />)}</tbody>
        </table>
      </div>
      {showNew && <SupplyRequestModal onClose={() => setShowNew(false)} onCreate={createRequest} />}
      {showParts && <PartOrdersModal onClose={() => setShowParts(false)} />}
    </div>
  );
}

function SupplyRequestModal({ onClose, onCreate }) {
  const [draft, setDraft] = useSo({ item: '', qty: '1 pc', deadline: 'Today', priority: 'normal', wo: '' });
  const valid = draft.item.trim().length > 2 && draft.qty.trim();
  return (
    <Modal title={tx('New request')} sub={tx('Create a purchasing task and notify the manager')} onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Cancel')}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={() => onCreate({ ...draft, item: draft.item.trim(), qty: draft.qty.trim() })}>
          {React.createElement(Icon.plus, { size: 15, stroke: 2.6 })} {tx('Create request')}
        </button>
      </>}>
      <div className="field"><label>{tx('Item')}</label><input className="input" value={draft.item} onChange={(e) => setDraft({ ...draft, item: e.target.value })} placeholder={tx('e.g. Front brake discs OEM (pair)')} autoFocus /></div>
      <div className="grid-2">
        <div className="field"><label>{tx('Quantity')}</label><input className="input" value={draft.qty} onChange={(e) => setDraft({ ...draft, qty: e.target.value })} /></div>
        <div className="field"><label>{tx('Order')}</label><input className="input" value={draft.wo} onChange={(e) => setDraft({ ...draft, wo: e.target.value })} placeholder="WO-1187" /></div>
      </div>
      <div className="grid-2">
        <div className="field"><label>{tx('Deadline')}</label><select className="select" value={draft.deadline} onChange={(e) => setDraft({ ...draft, deadline: e.target.value })}>{['Today', 'Tomorrow', 'In 2 days'].map((x) => <option key={x} value={x}>{tdate(x)}</option>)}</select></div>
        <div className="field"><label>{tx('Priority')}</label><select className="select" value={draft.priority} onChange={(e) => setDraft({ ...draft, priority: e.target.value })}>{['low', 'normal', 'high'].map((x) => <option key={x} value={x}>{tx(x[0].toUpperCase() + x.slice(1))}</option>)}</select></div>
      </div>
    </Modal>
  );
}

function PartOrdersModal({ onClose }) {
  const [orders, setOrders] = useSo(() => PAYOUTS.slice(0, 0).concat([
    { id: 'PO-441', wo: 'WO-1187', item: 'Front brake discs OEM (pair)', supplier: 'Inter Cars', status: 'ordered', eta: 'Tomorrow' },
    { id: 'PO-442', wo: 'WO-1185', item: 'White base coat (RAL 9003)', supplier: 'Lakmal', status: 'received', eta: 'Today' },
  ]));
  const receive = (id) => { setOrders((xs) => xs.map((x) => x.id === id ? { ...x, status: 'received', eta: 'Today' } : x)); toast(tx('Part marked as received'), 'package'); };
  return (
    <Modal wide title={tx('Part orders')} sub={tx('Track ordered parts and receiving status')} onClose={onClose}
      footer={<button className="btn btn-primary" onClick={onClose}>{tx('Done')}</button>}>
      <table className="tbl">
        <thead><tr><th>{tx('Order')}</th><th>{tx('Item')}</th><th>{tx('Supplier')}</th><th>{tx('ETA')}</th><th>{tx('Status')}</th><th></th></tr></thead>
        <tbody>{orders.map((o) => (
          <tr key={o.id}>
            <td><span className="mono tiny muted2">{o.wo}</span><div className="tiny muted">{o.id}</div></td>
            <td className="strong sec">{tx(o.item)}</td>
            <td>{o.supplier}</td>
            <td>{tdate(o.eta)}</td>
            <td><Badge kind={o.status === 'received' ? 'success' : 'accent'} pip>{tx(o.status === 'received' ? 'Received' : 'Ordered')}</Badge></td>
            <td style={{ textAlign: 'right' }}>{o.status !== 'received' && <button className="btn btn-outline sm" onClick={() => receive(o.id)}>{tx('Receive')}</button>}</td>
          </tr>
        ))}</tbody>
      </table>
    </Modal>
  );
}

/* =========================== FINANCES =========================== */
function FinancesView() {
  const [range, setRange] = useSo('Month');
  const [summaries, setSummaries] = useStoredState('ac.finance.summaries', () => ({
    month: readStored('ac.finance.month', null),
  }));
  const [invoice, setInvoice] = useSo(false);
  const period = range.toLowerCase();
  const apiSummary = summaries[period];
  const f = { ...FIN_SUMMARY, ...(apiSummary || {}) };
  const multiplier = range === 'Week' ? 0.32 : range === 'Quarter' ? 2.8 : 1;
  const scaled = (n) => Math.round((Number(n) || 0) * (apiSummary ? 1 : multiplier));
  useOpsEffect(() => {
    let cancelled = false;
    if (!AutoCareAPI.enabled()) return () => { cancelled = true; };
    AutoCareAPI.financeSummary(period)
      .then((summary) => {
        if (!cancelled && summary) setSummaries((current) => ({ ...current, [period]: summary }));
      })
      .catch((e) => console.warn('[AutoCareAPI] finance summary failed', e));
    return () => { cancelled = true; };
  }, [period]);
  const Label = ({ children, note }) => (
    <div className="group-label"><span>{children}</span><span className="ln" />{note && <span className="group-note">{note}</span>}</div>
  );
  const dueDate = f.invoiceDueDate || 'Jun 30';
  return (
    <div className="page view-fade" data-screen-label="Finances">
      <div className="page-head">
        <div><div className="page-title">{tx('Finances')}</div><div className="page-sub">{tx('Card payouts via Stripe Connect · cash commission accrued and invoiced separately')}</div></div>
        <span className="spacer" />
        <div className="seg">{['Week', 'Month', 'Quarter'].map((x) => <button key={x} className={range === x ? 'on' : ''} onClick={() => setRange(x)}>{tx(x)}</button>)}</div>
      </div>

      {/* ---- This month ---- */}
      <div className="fin-group">
        <Label note={range === 'Month' ? tx('June 2026') : tx(range)}>{range === 'Month' ? tx('This month') : tx(range)}</Label>
        <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
          <Stat label={tx('GMV (this month)')} icon="trend" value={`${(scaled(f.gmv) / 1000).toFixed(1)}k`} unit="zł" delta={tx('12% vs last month')} />
          <Stat label={tx('Net payout (card)')} icon="wallet" value={`${(scaled(f.netPayout) / 1000).toFixed(1)}k`} unit="zł" delta={tx('via Stripe')} deltaDir="flat" />
          <Stat label={tx('Cash collected')} icon="cash" value={`${(scaled(f.cashCollected) / 1000).toFixed(1)}k`} unit="zł" deltaDir="flat" />
          <Stat label={tx('Commission owed')} icon="receipt" value={zl(scaled(f.commissionOwed))} accent delta={fmt('invoice due {date}', { date: dueDate })} deltaDir="flat" />
        </div>
      </div>

      {/* ---- Today ---- */}
      <div className="fin-group">
        <Label>{tx('Today')}</Label>
        <div className="grid-2" style={{ alignItems: 'stretch' }}>
          <div className="card card-pad">
            <div className="between" style={{ marginBottom: 12 }}><span className="strong sec">{tx('Today’s money')}</span><Badge kind="cash">{tx('cash-first')}</Badge></div>
            <div className="total-row"><span>{tx('Collected (cash)')}</span><span className="v">{zl(3420)}</span></div>
            <div className="total-row"><span>{tx('Captured (card)')}</span><span className="v">{zl(1894)}</span></div>
            <div className="total-grand"><span className="lab">{tx('Gross today')}</span><span className="v" style={{ fontSize: 20 }}>{zl(5314)}</span></div>
          </div>
          <div className="card card-pad">
            <div className="between" style={{ marginBottom: 12 }}><span className="strong sec">{tx('Settlement status')}</span>{React.createElement(Icon.card, { size: 15, style: { color: 'var(--text-3)' } })}</div>
            <div className="total-row"><span>{tx('Next Stripe payout')}</span><span className="v">{zl(f.nextStripePayout || 1280)}</span></div>
            <div className="total-row muted"><span>{tx('Pending capture')}</span><span className="v">{zl(f.pendingCapture || 1510)}</span></div>
            <div className="divider" />
            <div className="total-row"><span>{tx('Commission owed (cash)')}</span><span className="v" style={{ color: 'var(--accent)' }}>{zl(f.commissionOwed)}</span></div>
            <div className="tiny muted" style={{ marginTop: 5 }}>{fmt('Invoiced monthly · due {date}', { date: dueDate })}</div>
          </div>
        </div>
      </div>

      {/* ---- Transactions ---- */}
      <div className="fin-group">
        <Label>{tx('Transactions')}</Label>
        <div className="grid-2" style={{ alignItems: 'start' }}>
          {/* card payouts */}
          <div className="card">
            <div className="card-hd">{React.createElement(Icon.card, { size: 16, style: { color: 'var(--text-2)' } })}<h3>{tx('Card payouts')}</h3><Badge kind="neutral">Stripe Connect</Badge></div>
            <table className="tbl">
              <thead><tr><th>{tx('Order')}</th><th style={{ textAlign: 'right' }}>{tx('Gross')}</th><th style={{ textAlign: 'right' }}>{tx('Fee')}</th><th style={{ textAlign: 'right' }}>{tx('Net')}</th><th>{tx('Status')}</th></tr></thead>
              <tbody>{PAYOUTS.map((p) => (
                <tr key={p.id}><td><span className="mono tiny muted2">{p.wo}</span><div className="tiny muted">{tdate(p.date)}</div></td>
                  <td className="num">{zl(p.gross)}</td><td className="num muted">−{zl(p.fee)}</td><td className="num strong">{zl(p.net)}</td>
                  <td>{p.status === 'paid' ? <Badge kind="success" pip>{tx('Paid')}</Badge> : <Badge kind="warning" pip>{tx('Pending')}</Badge>}</td></tr>
              ))}</tbody>
            </table>
          </div>

          {/* cash accruals */}
          <div className="card">
            <div className="card-hd">{React.createElement(Icon.cash, { size: 16, style: { color: 'var(--cash)' } })}<h3>{tx('Cash commission')}</h3><Badge kind="cash">{tx('accrued')}</Badge></div>
            <table className="tbl">
              <thead><tr><th>{tx('Order')}</th><th style={{ textAlign: 'right' }}>{tx('Collected')}</th><th style={{ textAlign: 'right' }}>{tx('Commission')}</th><th>{tx('Status')}</th></tr></thead>
              <tbody>{ACCRUALS.map((a) => (
                <tr key={a.id}><td><span className="mono tiny muted2">{a.wo}</span><div className="tiny muted">{tdate(a.date)}</div></td>
                  <td className="num">{zl(a.collected)}</td><td className="num strong">{zl(a.commission)}</td>
                  <td>{a.status === 'paid' ? <Badge kind="success" pip>{tx('Paid')}</Badge> : a.status === 'invoiced' ? <Badge kind="accent" pip>{tx('Invoiced')}</Badge> : <Badge kind="warning" pip>{tx('Accrued')}</Badge>}</td></tr>
              ))}</tbody>
            </table>
            <div className="card-ft between">
              <div><div className="tiny muted">{tx('Outstanding to platform')}</div><div className="mono strong" style={{ fontSize: 16 }}>{zl(scaled(f.commissionOwed))}</div></div>
              <button className="btn btn-primary sm" onClick={() => setInvoice(true)}>{tx('View invoice')}</button>
            </div>
          </div>
        </div>
      </div>
      {invoice && <InvoiceModal amount={scaled(f.commissionOwed)} dueDate={dueDate} onClose={() => setInvoice(false)} />}
    </div>
  );
}

function InvoiceModal({ amount, dueDate, onClose }) {
  const [paid, setPaid] = useSo(false);
  return (
    <Modal title={tx('Commission invoice')} sub="INV-2026-06 · AutoCare Platform" onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Close')}</button>
        <button className="btn btn-primary" disabled={paid} onClick={() => { setPaid(true); toast(tx('Invoice marked as paid'), 'checkCircle'); }}>
          {paid ? tx('Paid') : tx('Mark invoice paid')}
        </button>
      </>}>
      <div className="total-row"><span>{tx('Cash commission')}</span><span className="v">{zl(amount)}</span></div>
      <div className="total-row muted"><span>{tx('Due date')}</span><span className="v">{dueDate || 'Jun 30, 2026'}</span></div>
      <div className="divider" />
      <Badge kind={paid ? 'success' : 'warning'} pip>{paid ? tx('Paid') : tx('Pending')}</Badge>
    </Modal>
  );
}

/* ============================= TEAM ============================= */
const ROLE_DEFS = [
  { role: 'Manager',  spec: 'Reception',   admin: true,  desc: 'Full access · all orders, finances, pricing, team' },
  { role: 'Mechanic', spec: 'Mechanics',   admin: false, desc: 'Own assigned orders only' },
  { role: 'Painter',  spec: 'Paint',       admin: false, desc: 'Own assigned orders only' },
  { role: 'Bodywork', spec: 'Bodywork',    admin: false, desc: 'Own assigned orders only' },
  { role: 'PDR',      spec: 'PDR',         admin: false, desc: 'Own assigned orders only' },
  { role: 'Diagnostics', spec: 'Diagnostics', admin: false, desc: 'Own assigned orders only' },
];
const roleDef = (r) => ROLE_DEFS.find((d) => d.role === r) || ROLE_DEFS[1];

function InviteModal({ onClose, onInvite }) {
  const [name, setName] = useSo('');
  const [phone, setPhone] = useSo('');
  const [role, setRole] = useSo('Mechanic');
  const def = roleDef(role);
  const email = name.trim() ? name.trim().toLowerCase().replace(/[^a-z\s]/g, '').split(/\s+/).slice(0, 2).join('.') + '@krakowauto.pl' : '';
  const valid = name.trim().length > 2;
  return (
    <Modal title={tx('Invite team member')} sub={tx('They receive an SMS invite and set their own password on first login')} onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Cancel')}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={() => onInvite({ name: name.trim(), phone: phone.trim(), email, role, spec: def.spec, access: def.admin ? 'admin' : 'staff' })}>
          {React.createElement(Icon.mail, { size: 15 })} {tx('Send invite')}
        </button>
      </>}>
      <div className="field">
        <label>{tx('Full name')}</label>
        <input className="input" placeholder="e.g. Jan Kowalski" value={name} onChange={(e) => setName(e.target.value)} autoFocus />
        {email && <div className="hint">{tx('Login email:')} <b className="mono" style={{ color: 'var(--text-2)' }}>{email}</b></div>}
      </div>
      <div className="field">
        <label>{tx('Phone (for SMS invite)')}</label>
        <input className="input" placeholder="+48 ··· ··· ···" value={phone} onChange={(e) => setPhone(e.target.value)} />
      </div>
      <div className="field" style={{ marginBottom: 6 }}>
        <label>{tx('Role')}</label>
        <div className="wrap">
          {ROLE_DEFS.map((d) => (
            <button key={d.role} className={`btn sm ${role === d.role ? 'btn-primary' : 'btn-outline'}`} onClick={() => setRole(d.role)}>
              {React.createElement(Icon[d.admin ? 'shield' : 'wrench'], { size: 14 })} {tx(d.role)}
            </button>
          ))}
        </div>
      </div>
      <div className="card" style={{ background: 'var(--surface-2)', boxShadow: 'none', padding: '11px 13px', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        {React.createElement(Icon[def.admin ? 'shield' : 'user'], { size: 16, style: { color: def.admin ? 'var(--accent)' : 'var(--text-3)', marginTop: 1 } })}
        <div>
          <div className="sec strong" style={{ fontSize: 13 }}>{def.admin ? tx('Admin access') : tx('Limited access')}</div>
          <div className="tiny muted" style={{ marginTop: 2, lineHeight: 1.45 }}>{tx(def.desc)}</div>
        </div>
      </div>
    </Modal>
  );
}

function MemberModal({ member, onClose, onSave }) {
  const [draft, setDraft] = useSo(() => ({ ...member }));
  const def = roleDef(draft.role);
  return (
    <Modal title={tx('Edit team member')} sub={member.name} onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Cancel')}</button>
        <button className="btn btn-primary" onClick={() => onSave({ ...draft, spec: roleDef(draft.role).spec, access: roleDef(draft.role).admin ? 'admin' : 'staff' })}>
          {React.createElement(Icon.check, { size: 15, stroke: 2.6 })} {tx('Save member')}
        </button>
      </>}>
      <div className="row" style={{ gap: 13, marginBottom: 14 }}>
        <Avatar name={draft.name} size={44} accent={draft.active !== false} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="strong">{draft.name}</div>
          <div className="tiny muted">{draft.email || `${draft.id}@krakowauto.pl`}</div>
        </div>
        <Badge kind={draft.active === false ? 'danger' : 'success'} pip>{draft.active === false ? tx('Inactive') : tx('Active')}</Badge>
      </div>
      <div className="field">
        <label>{tx('Role')}</label>
        <div className="wrap">
          {ROLE_DEFS.map((d) => (
            <button key={d.role} className={`btn sm ${draft.role === d.role ? 'btn-primary' : 'btn-outline'}`} onClick={() => setDraft({ ...draft, role: d.role, spec: d.spec })}>
              {React.createElement(Icon[d.admin ? 'shield' : 'wrench'], { size: 14 })} {tx(d.role)}
            </button>
          ))}
        </div>
      </div>
      <div className="field">
        <label>{tx('Specialization')}</label>
        <select className="select" value={draft.spec} onChange={(e) => setDraft({ ...draft, spec: e.target.value })}>
          {[...new Set([...SHOP.specializations, ...ROLE_DEFS.map((r) => r.spec)])].map((x) => <option key={x} value={x}>{tx(x)}</option>)}
        </select>
      </div>
      <div className="card" style={{ background: 'var(--surface-2)', boxShadow: 'none', padding: '11px 13px', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        {React.createElement(Icon[def.admin ? 'shield' : 'user'], { size: 16, style: { color: def.admin ? 'var(--accent)' : 'var(--text-3)', marginTop: 1 } })}
        <div>
          <div className="sec strong" style={{ fontSize: 13 }}>{def.admin ? tx('Admin access') : tx('Limited access')}</div>
          <div className="tiny muted" style={{ marginTop: 2, lineHeight: 1.45 }}>{tx(def.desc)}</div>
        </div>
      </div>
    </Modal>
  );
}

function TeamView() {
  const [members, setMembers] = useStoredState('ac.team', () => TEAM.map((u) => ({ ...u })));
  const [invites, setInvites] = useStoredState('ac.team.invites', []);
  const [showInvite, setShowInvite] = useSo(false);
  const [removing, setRemoving] = useSo(null);
  const [editing, setEditing] = useSo(null);

  const activeMembers = members.filter((m) => m.active !== false);
  const admins = activeMembers.filter((m) => roleDef(m.role).admin).length;

  const invite = async ({ name, phone, email, role, spec, access }) => {
    const apiInvite = await AutoCareAPI.inviteMember({ name, phone, email, role, spec, access }).catch((e) => (console.warn('[AutoCareAPI] invite failed', e), null));
    const id = 'u' + (Date.now() % 100000);
    const initials = name.split(' ').map((w) => w[0]).slice(0, 2).join('').toUpperCase();
    setInvites((x) => [...x, apiInvite || { id, name, phone, email, role, spec, access, initials, pending: true }]);
    setShowInvite(false);
    toast(apiInvite ? fmt('Invite sent to {name} · backend synced', { name: name.split(' ')[0] }) : fmt('Invite sent to {name} · SMS delivered', { name: name.split(' ')[0] }), 'mail');
  };
  const cancelInvite = async (id) => {
    const invite = invites.find((x) => x.id === id);
    if (invite) await AutoCareAPI.revokeInvite(invite).catch((e) => console.warn('[AutoCareAPI] revoke invite failed', e));
    setInvites((x) => x.filter((i) => i.id !== id));
    toast(tx('Invite revoked'), 'xCircle');
  };
  const resendInvite = async (id) => {
    const i = invites.find((x) => x.id === id);
    if (!i) return;
    await AutoCareAPI.resendInvite(i).catch((e) => console.warn('[AutoCareAPI] resend invite failed', e));
    toast(fmt('Invite re-sent to {name}', { name: i.name.split(' ')[0] }), 'mail');
  };
  const confirmRemove = async () => {
    const u = removing;
    await AutoCareAPI.deactivateMember(u).catch((e) => console.warn('[AutoCareAPI] deactivate member failed', e));
    setMembers((m) => m.map((x) => x.id === u.id ? { ...x, active: false } : x));
    setRemoving(null);
    toast(fmt('{name} deactivated · access revoked', { name: u.name.split(' ')[0] }), 'trash');
  };
  const saveMember = (member) => {
    setMembers((items) => items.map((item) => item.id === member.id ? member : item));
    setEditing(null);
    toast(tx('Team member updated'), 'users');
  };
  const reactivate = (member) => {
    setMembers((items) => items.map((item) => item.id === member.id ? { ...item, active: true } : item));
    toast(fmt('{name} reactivated', { name: member.name.split(' ')[0] }), 'checkCircle');
  };

  return (
    <div className="page view-fade" data-screen-label="Team">
      <div className="page-head">
        <div><div className="page-title">{tx('Team & roles')}</div><div className="page-sub">{tx('Add or remove staff and set what each role can see · staff see only the orders assigned to them')}</div></div>
        <span className="spacer" />
        <button className="btn btn-primary" onClick={() => setShowInvite(true)}>{React.createElement(Icon.userPlus, { size: 16, stroke: 2.4 })} {tx('Invite member')}</button>
      </div>

      <div className="grid-3" style={{ marginBottom: 18 }}>
        <Stat label={tx('Team members')} icon="users" value={String(activeMembers.length)} delta={fmt('{a} admin · {b} staff', { a: admins, b: activeMembers.length - admins })} deltaDir="flat" />
        <Stat label={tx('Pending invites')} icon="mail" value={String(invites.length)} accent={invites.length > 0} delta={invites.length ? tx('awaiting first login') : tx('none')} deltaDir="flat" />
        <Stat label={tx('Specializations covered')} icon="shield" value={String(new Set(activeMembers.map((m) => m.spec)).size)} deltaDir="flat" />
      </div>

      {/* pending invites */}
      {invites.length > 0 && (
        <div className="card" style={{ marginBottom: 16 }}>
          <div className="card-hd">{React.createElement(Icon.mail, { size: 16, style: { color: 'var(--text-2)' } })}<h3>{tx('Pending invites')}</h3><Badge kind="accent" pip>{invites.length}</Badge></div>
          {invites.map((i) => (
            <div className="list-item" key={i.id}>
              <Avatar name={i.name} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="strong sec">{i.name}</div>
                <div className="tiny muted">{tx(i.role)} · {tx(i.spec)}{i.phone ? ' · ' + i.phone : ''}</div>
              </div>
              <Badge kind="warning" pip>{tx('Invite sent')}</Badge>
              <button className="btn btn-ghost sm" onClick={() => resendInvite(i.id)}>{tx('Resend')}</button>
              <button className="btn btn-danger sm" onClick={() => cancelInvite(i.id)}>{tx('Revoke')}</button>
            </div>
          ))}
        </div>
      )}

      {/* active members */}
      <div className="card">
        <div className="card-hd">{React.createElement(Icon.users, { size: 16, style: { color: 'var(--text-2)' } })}<h3>{tx('Team members')}</h3><Badge kind="neutral">{members.length}</Badge></div>
        <table className="tbl">
          <thead><tr><th>{tx('Member')}</th><th>{tx('Role')}</th><th>{tx('Specialization')}</th><th>{tx('Access')}</th><th>{tx('Status')}</th><th style={{ textAlign: 'center' }}>{tx('Active orders')}</th><th style={{ textAlign: 'right' }}>{tx('Manage')}</th></tr></thead>
          <tbody>{members.map((u) => {
            const def = roleDef(u.role);
            return (
              <tr key={u.id} style={u.active === false ? { opacity: .58 } : null}>
                <td><div className="row" style={{ gap: 10 }}><Avatar name={u.name} accent={u.you} /><div style={{ minWidth: 0 }}><div className="strong sec" style={{ whiteSpace: 'nowrap' }}>{u.name}{u.you && <span className="tiny muted"> · {tx('you')}</span>}</div><div className="tiny muted mono">{u.id}@krakowauto.pl</div></div></div></td>
                <td><Badge kind={def.admin ? 'accent' : 'neutral'} pip>{tx(u.role)}</Badge></td>
                <td className="muted">{tx(u.spec)}</td>
                <td>{def.admin
                  ? <span className="row tiny" style={{ gap: 6 }}>{React.createElement(Icon.shield, { size: 13, style: { color: 'var(--accent)' } })}<b>{tx('All orders')}</b> · {tx('finances')} · {tx('pricing')}</span>
                  : <span className="tiny muted">{tx('Own assigned orders only')}</span>}</td>
                <td><Badge kind={u.active === false ? 'danger' : 'success'} pip>{u.active === false ? tx('Inactive') : tx('Active')}</Badge></td>
                <td className="num" style={{ textAlign: 'center' }}>{def.admin ? '—' : ((u.id.charCodeAt(1) % 3) + 1)}</td>
                <td style={{ textAlign: 'right' }}>
                  {u.you
                    ? <span className="tiny muted">{tx('You')}</span>
                    : <div className="row" style={{ justifyContent: 'flex-end', gap: 6 }}>
                        <button className="btn btn-outline sm" onClick={() => setEditing(u)}>{React.createElement(Icon.edit, { size: 14 })} {tx('Edit')}</button>
                        {u.active === false
                          ? <button className="btn btn-primary sm" onClick={() => reactivate(u)}>{tx('Activate')}</button>
                          : <button className="btn btn-danger sm" onClick={() => setRemoving(u)}>{React.createElement(Icon.trash, { size: 14 })} {tx('Deactivate')}</button>}
                      </div>}
                </td>
              </tr>
            );
          })}</tbody>
        </table>
      </div>

      {showInvite && <InviteModal onClose={() => setShowInvite(false)} onInvite={invite} />}
      {editing && <MemberModal member={editing} onClose={() => setEditing(null)} onSave={saveMember} />}
      {removing && (
        <Modal title={tx('Deactivate team member')} onClose={() => setRemoving(null)}
          footer={<>
            <button className="btn btn-ghost" onClick={() => setRemoving(null)}>{tx('Cancel')}</button>
            <button className="btn btn-danger" onClick={confirmRemove}>{React.createElement(Icon.trash, { size: 15 })} {tx('Deactivate')} {removing.name.split(' ')[0]}</button>
          </>}>
          <div className="row" style={{ gap: 13, marginBottom: 14 }}>
            <Avatar name={removing.name} size={44} />
            <div style={{ minWidth: 0 }}><div className="strong" style={{ whiteSpace: 'nowrap' }}>{removing.name}</div><div className="tiny muted">{tx(removing.role)} · {tx(removing.spec)}</div></div>
          </div>
          <div className="card" style={{ background: 'var(--danger-soft)', boxShadow: 'none', border: 'none', padding: '12px 14px', display: 'flex', gap: 10 }}>
            {React.createElement(Icon.alert, { size: 17, style: { color: 'var(--danger)', flex: '0 0 auto', marginTop: 1 } })}
            <div className="tiny" style={{ color: 'var(--danger)', lineHeight: 1.5 }}>
              {tx('Their login is revoked immediately, but the profile stays in history. Any orders assigned to them are released back to the unassigned pool — reassign them before they go unattended.')}
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}

/* ===================== schedule / reviews ===================== */
function ScheduleView() {
  const [slots, setSlots] = useStoredState('ac.schedule', [
    { id: 'sl1', time: 'Today · 09:00', bay: 'Bay 1', spec: 'Mechanics', status: 'booked', order: 'WO-1187' },
    { id: 'sl2', time: 'Today · 11:00', bay: 'Bay 2', spec: 'Diagnostics', status: 'open', order: '' },
    { id: 'sl3', time: 'Tomorrow · 14:30', bay: 'Paint booth', spec: 'Paint', status: 'blocked', order: 'Supplier delivery' },
  ]);
  const [showBlock, setShowBlock] = useSo(false);
  const toggle = (id) => setSlots((xs) => xs.map((s) => s.id === id ? { ...s, status: s.status === 'open' ? 'blocked' : 'open', order: s.status === 'open' ? 'Manual block' : '' } : s));
  const addBlock = (draft) => {
    setSlots((xs) => [{ id: 'sl' + Date.now(), status: 'blocked', ...draft }, ...xs]);
    setShowBlock(false);
    toast(tx('Schedule block added'), 'calendar');
  };
  return (
    <div className="page view-fade" data-screen-label="Schedule">
      <div className="page-head">
        <div><div className="page-title">{tx('Schedule')}</div><div className="page-sub">{tx('Working hours, slots & box capacity')}</div></div>
        <span className="spacer" />
        <button className="btn btn-primary" onClick={() => setShowBlock(true)}>{React.createElement(Icon.plus, { size: 15, stroke: 2.6 })} {tx('Block slot')}</button>
      </div>
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <Stat label={tx('Open slots')} icon="calendar" value={String(slots.filter((s) => s.status === 'open').length)} />
        <Stat label={tx('Booked slots')} icon="wrench" value={String(slots.filter((s) => s.status === 'booked').length)} />
        <Stat label={tx('Blocked slots')} icon="alert" value={String(slots.filter((s) => s.status === 'blocked').length)} accent />
      </div>
      <div className="card">
        <table className="tbl">
          <thead><tr><th>{tx('Time')}</th><th>{tx('Bay')}</th><th>{tx('Specialization')}</th><th>{tx('Status')}</th><th>{tx('Order')}</th><th></th></tr></thead>
          <tbody>{slots.map((s) => (
            <tr key={s.id}>
              <td className="strong sec">{tdate(s.time)}</td>
              <td>{s.bay}</td>
              <td><Badge kind="outline">{tx(s.spec)}</Badge></td>
              <td><Badge kind={s.status === 'open' ? 'success' : s.status === 'booked' ? 'accent' : 'warning'} pip>{tx(s.status === 'open' ? 'Open' : s.status === 'booked' ? 'Booked' : 'Blocked')}</Badge></td>
              <td className="muted">{s.order || '—'}</td>
              <td style={{ textAlign: 'right' }}>{s.status !== 'booked' && <button className="btn btn-outline sm" onClick={() => toggle(s.id)}>{s.status === 'open' ? tx('Block') : tx('Open')}</button>}</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
      {showBlock && <ScheduleBlockModal onClose={() => setShowBlock(false)} onCreate={addBlock} />}
    </div>
  );
}

function ScheduleBlockModal({ onClose, onCreate }) {
  const [draft, setDraft] = useSo({ time: 'Tomorrow · 09:00', bay: 'Bay 1', spec: 'Mechanics', order: 'Manual block' });
  return (
    <Modal title={tx('Block slot')} sub={tx('Reserve capacity for internal work or supplier delays')} onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Cancel')}</button>
        <button className="btn btn-primary" onClick={() => onCreate(draft)}>{tx('Create block')}</button>
      </>}>
      <div className="grid-2">
        <div className="field"><label>{tx('Time')}</label><input className="input" value={draft.time} onChange={(e) => setDraft({ ...draft, time: e.target.value })} /></div>
        <div className="field"><label>{tx('Bay')}</label><input className="input" value={draft.bay} onChange={(e) => setDraft({ ...draft, bay: e.target.value })} /></div>
      </div>
      <div className="field"><label>{tx('Reason')}</label><input className="input" value={draft.order} onChange={(e) => setDraft({ ...draft, order: e.target.value })} /></div>
    </Modal>
  );
}

function ReviewsView() {
  const [reviews, setReviews] = useStoredState('ac.reviews', [
    { id: 'r1', customer: 'Anna Nowak', rating: 5, text: 'Fast oil service and clear pricing.', replied: false },
    { id: 'r2', customer: 'Marek Kowalczyk', rating: 4, text: 'Good communication on extra brake work.', replied: true },
  ]);
  const reply = (id) => { setReviews((xs) => xs.map((r) => r.id === id ? { ...r, replied: true } : r)); toast(tx('Reply published'), 'chat'); };
  return (
    <div className="page view-fade" data-screen-label="Reviews">
      <div className="page-head"><div><div className="page-title">{tx('Reviews')}</div><div className="page-sub">{tx('Customer ratings that build your shop rating')}</div></div></div>
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <Stat label={tx('Rating')} icon="star" value={String(SHOP.rating)} />
        <Stat label={tx('Reviews')} icon="chat" value={String(SHOP.reviews)} />
        <Stat label={tx('Needs reply')} icon="mail" value={String(reviews.filter((r) => !r.replied).length)} accent />
      </div>
      <div className="card">
        {reviews.map((r) => (
          <div className="list-item" key={r.id}>
            <Avatar name={r.customer} />
            <div style={{ flex: 1, minWidth: 0 }}><div className="strong sec">{r.customer} · {'★'.repeat(r.rating)}</div><div className="tiny muted">{r.text}</div></div>
            {r.replied ? <Badge kind="success" pip>{tx('Replied')}</Badge> : <button className="btn btn-primary sm" onClick={() => reply(r.id)}>{tx('Reply')}</button>}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============================ SETTINGS ============================ */
function TagPicker({ title, options, selected, onClose, onToggle }) {
  return (
    <Modal title={title} onClose={onClose} footer={<button className="btn btn-primary" onClick={onClose}>{tx('Done')}</button>}>
      <div className="pickgrid">
        {options.map((o) => {
          const on = selected.includes(o);
          return (
            <button key={o} className={`pickchip ${on ? 'on' : ''}`} onClick={() => onToggle(o)}>
              {on && React.createElement(Icon.check, { size: 14, stroke: 2.8 })}
              {o}
            </button>
          );
        })}
      </div>
    </Modal>
  );
}

function Capability({ icon, title, sub, on, onToggle, children }) {
  return (
    <div className="cap">
      <div className={`cap-ic ${on ? 'on' : ''}`}>{React.createElement(Icon[icon], { size: 19 })}</div>
      <div className="cap-main">
        <div className="row" style={{ alignItems: 'flex-start', gap: 10 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="cap-title">{tx(title)}</div>
            <div className="cap-sub">{tx(sub)}</div>
          </div>
          <Switch on={on} onClick={onToggle} />
        </div>
        {on && children}
      </div>
    </div>
  );
}

function SettingsView() {
  const [profile, setProfile] = useStoredState('ac.shopProfile', SHOP);
  const [warranty, setWarranty] = useStoredState('ac.settings.warranty', SHOP.warranty);
  const [brands, setBrands] = useStoredState('ac.settings.warrantyBrands', SHOP.warrantyBrands);
  const [insurance, setInsurance] = useStoredState('ac.settings.insurance', SHOP.insurance);
  const [insurers, setInsurers] = useStoredState('ac.settings.insurers', SHOP.insurers);
  const [picker, setPicker] = useSo(null); // 'brands' | 'insurers'
  const [dirty, setDirty] = useSo(false);
  const [newSpec, setNewSpec] = useSo('');
  const touch = (fn) => (...a) => { fn(...a); setDirty(true); };

  const toggleBrand = touch((b) => setBrands((x) => x.includes(b) ? x.filter((i) => i !== b) : [...x, b]));
  const toggleInsurer = touch((b) => setInsurers((x) => x.includes(b) ? x.filter((i) => i !== b) : [...x, b]));

  const save = async () => {
    const result = await AutoCareAPI.saveSettings({ profile, warranty, brands, insurance, insurers }).catch((e) => (console.warn('[AutoCareAPI] settings save failed', e), null));
    setDirty(false);
    toast(result ? tx('Settings saved to backend') : tx('Settings saved'), 'check');
  };
  const updateProfile = (field, value) => {
    setProfile((current) => ({ ...current, [field]: value }));
    setDirty(true);
  };
  const specs = profile.specializations || SHOP.specializations;
  const addSpec = () => {
    const value = newSpec.trim();
    if (!value || specs.includes(value)) return;
    updateProfile('specializations', [...specs, value]);
    setNewSpec('');
  };
  const removeSpec = (value) => updateProfile('specializations', specs.filter((item) => item !== value));

  return (
    <div className="page view-fade" data-screen-label="Settings">
      <div className="page-head">
        <div><div className="page-title">{tx('Settings')}</div><div className="page-sub">{tx('Shop profile, Stripe Connect, monetization')}</div></div>
        <span className="spacer" />
        <button className="btn btn-primary" disabled={!dirty} onClick={save}>{React.createElement(Icon.check, { size: 15, stroke: 2.6 })} {tx('Save changes')}</button>
      </div>

      <div className="settings-grid">
        <div className="col" style={{ gap: 18 }}>
          {/* shop profile */}
          <div className="card">
            <div className="card-hd">{React.createElement(Icon.settings, { size: 16, style: { color: 'var(--text-2)' } })}<h3>{tx('Shop profile')}</h3></div>
            <div className="card-pad">
              <div className="row" style={{ gap: 14, alignItems: 'flex-start', marginBottom: 14 }}>
                <Avatar name={profile.name} photo={profile.photo} size={64} accent />
                <div style={{ flex: 1 }}>
                  <div className="field" style={{ marginBottom: 0 }}>
                    <label>{tx('Workshop photo')}</label>
                    <input className="input" type="file" accept="image/png,image/jpeg,image/webp" onChange={(e) => {
                      const file = e.target.files && e.target.files[0];
                      if (file) readImageFile(file, (photo) => updateProfile('photo', photo));
                    }} />
                    <div className="hint">{tx('Shown in the workshop switcher, profile and customer marketplace preview.')}</div>
                  </div>
                </div>
              </div>
              <div className="grid-2">
                <div className="field"><label>{tx('Shop name')}</label><input className="input" value={profile.name} onChange={(e) => updateProfile('name', e.target.value)} /></div>
                <div className="field"><label>{tx('Phone')}</label><input className="input" value={profile.phone} onChange={(e) => updateProfile('phone', e.target.value)} /></div>
              </div>
              <div className="field"><label>{tx('Address')}</label><input className="input" value={profile.address} onChange={(e) => updateProfile('address', e.target.value)} /></div>
              <div className="grid-2">
                <div className="field"><label>{tx('City')}</label><input className="input" value={profile.city} onChange={(e) => updateProfile('city', e.target.value)} /></div>
                <div className="field"><label>{tx('Opening hours')}</label><input className="input" value={profile.hours} onChange={(e) => updateProfile('hours', e.target.value)} /></div>
              </div>
              <div className="field"><label>{tx('Description')}</label><textarea className="textarea" value={profile.description || ''} onChange={(e) => updateProfile('description', e.target.value)} /></div>
              <div className="field"><label>{tx('Website')}</label><input className="input" value={profile.website || ''} onChange={(e) => updateProfile('website', e.target.value)} /></div>
              <div className="field" style={{ marginBottom: 0 }}>
                <label>{tx('Specializations')}</label>
                <div className="tagrow" style={{ marginBottom: 10 }}>
                  {specs.map((s) => <span className="tagchip" key={s}>{tx(s)}<button onClick={() => removeSpec(s)}>{React.createElement(Icon.x, { size: 12, stroke: 2.6 })}</button></span>)}
                </div>
                <div className="row">
                  <input className="input" value={newSpec} onChange={(e) => setNewSpec(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') addSpec(); }} placeholder={tx('e.g. Electric vehicles')} />
                  <button className="btn btn-outline" onClick={addSpec}>{tx('Add')}</button>
                </div>
              </div>
            </div>
          </div>

          {/* marketplace capabilities */}
          <div className="card">
            <div className="card-hd">{React.createElement(Icon.shield, { size: 16, style: { color: 'var(--text-2)' } })}<h3>{tx('Marketplace capabilities')}</h3></div>
            <div className="card-pad" style={{ paddingTop: 4, paddingBottom: 8 }}>

              <Capability icon="award" title="Warranty repair" sub="Authorized for manufacturer warranty repairs" on={warranty} onToggle={touch(() => setWarranty((v) => !v))}>
                <div className="cap-editor">
                  <div className="field" style={{ marginBottom: 9 }}><label style={{ marginBottom: 0 }}>{tx('Authorized brands')}</label></div>
                  <div className="tagrow">
                    {brands.length === 0 && <span className="tiny muted" style={{ padding: '4px 0' }}>{tx('No brands selected yet')}</span>}
                    {brands.map((b) => (
                      <span className="tagchip" key={b}>{b}<button onClick={() => toggleBrand(b)}>{React.createElement(Icon.x, { size: 12, stroke: 2.6 })}</button></span>
                    ))}
                    <button className="tagchip-add" onClick={() => setPicker('brands')}>{React.createElement(Icon.plus, { size: 13, stroke: 2.6 })}{tx('Add brand')}</button>
                  </div>
                </div>
              </Capability>

              <Capability icon="shieldCheck" title="Insurance repair" sub="Settles repairs directly with insurers" on={insurance} onToggle={touch(() => setInsurance((v) => !v))}>
                <div className="cap-editor">
                  <div className="field" style={{ marginBottom: 9 }}><label style={{ marginBottom: 0 }}>{tx('Partner insurers')}</label></div>
                  <div className="tagrow">
                    {insurers.map((b) => (
                      <span className="tagchip" key={b}>{b}<button onClick={() => toggleInsurer(b)}>{React.createElement(Icon.x, { size: 12, stroke: 2.6 })}</button></span>
                    ))}
                    <button className="tagchip-add" onClick={() => setPicker('insurers')}>{React.createElement(Icon.plus, { size: 13, stroke: 2.6 })}{tx('Add insurer')}</button>
                  </div>
                </div>
              </Capability>

            </div>
            <div className="card-ft" style={{ display: 'flex', gap: 9, color: 'var(--text-3)' }}>
              {React.createElement(Icon.alert, { size: 14, style: { flex: '0 0 auto', marginTop: 1 } })}
              <span className="tiny" style={{ lineHeight: 1.5 }}>{tx('These capabilities appear as filters and badges to clients searching the marketplace.')}</span>
            </div>
          </div>
        </div>

        {/* client preview */}
        <div className="col" style={{ gap: 14 }}>
          <div className="group-label" style={{ margin: 0 }}>{tx('How clients see you')}<span className="ln" /></div>
          <div className="preview">
            <div className="preview-img">{profile.photo ? <img src={profile.photo} alt="" /> : (profile.name || SHOP.name).split(' ').map((w) => w[0]).slice(0, 2).join('').toUpperCase()}</div>
            <div style={{ padding: 14 }}>
              <div className="strong" style={{ fontSize: 14.5, letterSpacing: '-0.01em' }}>{profile.name}</div>
              {profile.description && <div className="tiny muted" style={{ marginTop: 5, lineHeight: 1.45 }}>{tx(profile.description)}</div>}
              <div className="row" style={{ gap: 6, marginTop: 6 }}>
                <span className="row" style={{ gap: 3, color: 'var(--warning)' }}>{React.createElement(Icon.star, { size: 13, fill: 'currentColor', stroke: 0 })}<b style={{ color: 'var(--text)', fontSize: 12.5 }}>{SHOP.rating}</b></span>
                <span className="tiny muted">· {SHOP.reviews} {tx('reviews')}</span>
              </div>
              <div className="row" style={{ gap: 6, marginTop: 11, flexWrap: 'wrap' }}>
                <Badge kind="success" pip>{tx('Verified shop')}</Badge>
                {warranty && <span className="badge warranty">{React.createElement(Icon.award, { size: 12, stroke: 2.3 })}{tx('Warranty repair')}</span>}
                {insurance && <span className="badge accent">{React.createElement(Icon.shield, { size: 12, stroke: 2.3 })}{tx('Insurance')}</span>}
              </div>
              {warranty && brands.length > 0 && (
                <div className="row" style={{ gap: 5, marginTop: 10, flexWrap: 'wrap' }}>
                  {brands.slice(0, 5).map((b) => <span className="badge outline" key={b} style={{ fontSize: 11 }}>{b}</span>)}
                  {brands.length > 5 && <span className="badge outline" style={{ fontSize: 11 }}>+{brands.length - 5}</span>}
                </div>
              )}
            </div>
          </div>
          <div className="group-label" style={{ margin: '6px 0 0' }}>{tx('Specializations')}<span className="ln" /></div>
          <div className="row" style={{ gap: 6, flexWrap: 'wrap' }}>
            {specs.map((s) => <Badge kind="outline" key={s}>{tx(s)}</Badge>)}
          </div>
        </div>
      </div>

      {picker === 'brands' && <TagPicker title={tx('Select brands')} options={WARRANTY_BRANDS} selected={brands} onToggle={toggleBrand} onClose={() => setPicker(null)} />}
      {picker === 'insurers' && <TagPicker title={tx('Select insurers')} options={INSURERS} selected={insurers} onToggle={toggleInsurer} onClose={() => setPicker(null)} />}
    </div>
  );
}

Object.assign(window, { PricingView, PurchasingView, FinancesView, TeamView, ScheduleView, ReviewsView, SettingsView });
