// views-main.jsx — Overview, Bookings, Work Orders list.
const { useState: useSt } = React;

function ProposeSlotModal({ booking, onClose, onSave }) {
  const [slot, setSlot] = useSt('Tomorrow · 10:00');
  const [note, setNote] = useSt('');
  return (
    <Modal title={tx('Propose new slot')} sub={booking.customer + ' · ' + booking.vehicle.make + ' ' + booking.vehicle.model} onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Cancel')}</button>
        <button className="btn btn-primary" onClick={() => onSave(slot, note)}>{React.createElement(Icon.calendar, { size: 15 })} {tx('Send proposal')}</button>
      </>}>
      <div className="field">
        <label>{tx('Requested slot')}</label>
        <select className="select" value={slot} onChange={(e) => setSlot(e.target.value)}>
          {['Today · 16:30', 'Tomorrow · 10:00', 'Tomorrow · 14:30', 'In 2 days · 09:00'].map((x) => <option key={x} value={x}>{tdate(x)}</option>)}
        </select>
      </div>
      <div className="field" style={{ marginBottom: 0 }}>
        <label>{tx('Message to customer')}</label>
        <textarea className="textarea" value={note} onChange={(e) => setNote(e.target.value)} placeholder={tx('Optional note…')} />
      </div>
    </Modal>
  );
}

/* ============================ OVERVIEW ============================ */
function OverviewView({ go }) {
  const [bookings] = useStoredState('ac.bookings', BOOKINGS);
  const [done] = useStoredState('ac.bookings.done', {});
  const [orders] = useStoredState('ac.workOrders', WORK_ORDERS);
  const [supply] = useStoredState('ac.supply', SUPPLY);
  const [quotes] = useStoredState('ac.quoteRequests', QUOTE_REQUESTS);
  const pendingBookings = bookings.filter((b) => !done[b.id]);
  const openQuotes = quotes.filter((q) => q.status === 'open');
  const activeOrders = orders.filter((w) => ['accepted', 'in_progress', 'ready'].includes(w.status));
  const ticketTotal = orders.reduce((sum, w) => sum + (w.id === HERO.id ? (readStored('ac.heroTickets', HERO.tickets).length || 0) : (w.ticketsCount || 0)), 0);
  return (
    <div className="page view-fade" data-screen-label="Overview">
      <div className="page-head">
        <div>
          <div className="page-title">{tx('Good morning')}, Marta</div>
          <div className="page-sub">{SHOP.name} · {new Date().toLocaleDateString(i18nLocale(), { weekday: 'long', month: 'long', day: 'numeric' })}</div>
        </div>
        <span className="spacer" />
        <button className="btn btn-outline" onClick={() => go('schedule')}>{React.createElement(Icon.calendar, { size: 15 })} {tx('Schedule')}</button>
        <button className="btn btn-primary" onClick={() => go('bookings')}>{React.createElement(Icon.inbox, { size: 15 })} {tx('Review requests')}</button>
      </div>

      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
        <Stat label={tx('Awaiting confirmation')} icon="inbox" value={String(pendingBookings.length)} delta={tx('2 new today')} />
        <Stat label={tx('Price requests')} icon="tag" value={String(openQuotes.length)} accent delta={tx('open for offers')} deltaDir="flat" />
        <Stat label={tx('Active work orders')} icon="wrench" value={String(activeOrders.length)} delta={tx('on track')} deltaDir="flat" />
        <Stat label={tx('Tickets awaiting client')} icon="tag" value={String(ticketTotal)} delta={tx('avg 18 min to decision')} deltaDir="flat" />
      </div>

      {/* incoming requests — full width */}
      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-hd">
          {React.createElement(Icon.inbox, { size: 17, style: { color: 'var(--text-2)' } })}
          <h3>{tx('New requests')}</h3>
          <Badge kind="warning" pip>{pendingBookings.length} {tx('awaiting')}</Badge>
          <span className="spacer" />
          <button className="btn btn-ghost sm" onClick={() => go('bookings')}>{tx('View all')} {React.createElement(Icon.chevR, { size: 14 })}</button>
        </div>
        {pendingBookings.map((b) => {
          const total = b.services.reduce((a, id) => a + displayed(svc(id)?.net || 0), 0);
          return (
            <div className="list-item clickable" key={b.id} onClick={() => go('bookings')}>
              <VehicleCell v={b.vehicle} sub={b.customer} />
              <span className="spacer" />
              <div className="wrap" style={{ justifyContent: 'flex-end', maxWidth: 280 }}>
                {b.services.map((id) => <Badge key={id} kind="outline">{tx(svc(id)?.name || id)}</Badge>)}
              </div>
              <div className="row" style={{ gap: 7, minWidth: 132, justifyContent: 'flex-end', color: 'var(--text-2)' }}>
                {React.createElement(Icon.clock || Icon.calendar, { size: 14, style: { color: 'var(--text-3)' } })}
                <span className="sec strong" style={{ fontSize: 13, whiteSpace: 'nowrap' }}>{tdate(b.slot)}</span>
              </div>
              <div style={{ textAlign: 'right', minWidth: 92 }}>
                <div className="mono strong">{tx('from')} {zl(total)}</div>
                <div className="row" style={{ gap: 6, justifyContent: 'flex-end', marginTop: 3 }}>
                  <PayBadge method={b.method} />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-hd">
          {React.createElement(Icon.tag, { size: 17, style: { color: 'var(--text-2)' } })}
          <h3>{tx('Open price requests')}</h3>
          <Badge kind="accent" pip>{openQuotes.length} {tx('open')}</Badge>
          <span className="spacer" />
          <button className="btn btn-ghost sm" onClick={() => go('quotes')}>{tx('View all')} {React.createElement(Icon.chevR, { size: 14 })}</button>
        </div>
        {openQuotes.slice(0, 3).map((q) => {
          const offers = [...(q.offers || [])].sort((a, b) => a.price - b.price);
          const mine = offers.find((o) => o.workshopId === CURRENT_WORKSHOP_ID);
          return (
            <div className="list-item clickable" key={q.id} onClick={() => go('quotes')}>
              <VehicleCell v={q.vehicle} sub={q.customer} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="strong sec">{tx(q.title)}</div>
                <div className="tiny muted">{q.id} · {tx(q.created)} · {offers.length} {tx('offers')}</div>
              </div>
              <Badge kind={mine ? 'success' : 'warning'} pip>{mine ? tx('Your offer sent') : tx('Needs your price')}</Badge>
              <div className="mono strong" style={{ minWidth: 98, textAlign: 'right' }}>{offers.length ? `${tx('from')} ${zl(offers[0].price)}` : tx('No offers')}</div>
            </div>
          );
        })}
      </div>

      {/* active work orders snapshot — full width */}
      <div className="card">
        <div className="card-hd">{React.createElement(Icon.wrench, { size: 16, style: { color: 'var(--text-2)' } })}
          <h3>{tx('Active work orders')}</h3><span className="spacer" />
          <button className="btn btn-ghost sm" onClick={() => go('orders')}>{tx('Open board')} {React.createElement(Icon.chevR, { size: 14 })}</button></div>
        <table className="tbl">
          <tbody>
            {activeOrders.map((w) => (
              <tr className="clickable" key={w.id} onClick={() => go('workorder', w.id)}>
                <td style={{ width: 240 }}><VehicleCell v={w.vehicle} sub={w.customer} /></td>
                <td><span className="mono tiny muted">{w.id}</span></td>
                <td><StatusBadge status={w.status} /></td>
                <td><PayBadge method={w.method} /></td>
                <td className="num">{zl((w.baseNet ? displayed(w.baseNet) : 0) + (w.ticketsNet ? displayed(w.ticketsNet) : 0) || displayed(520))}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* supply requests — full width */}
      <div className="card card-pad" style={{ marginTop: 18 }}>
        <div className="between" style={{ marginBottom: 12 }}>
          <span className="strong sec">{tx('Supply requests')}</span>
          <div className="row" style={{ gap: 10 }}>
            <Badge kind="danger">{tx('1 overdue')}</Badge>
            <button className="btn btn-ghost sm" onClick={() => go('purchasing')}>{tx('Open purchasing')} {React.createElement(Icon.chevR, { size: 14 })}</button>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {supply.filter((s) => ['open', 'overdue'].includes(s.status)).slice(0, 3).map((s) => (
            <div className="between" key={s.id} style={{ gap: 10, padding: '12px 14px', border: '1px solid var(--border)', borderRadius: 10 }}>
              <div style={{ minWidth: 0, flex: 1 }}><div className="sec strong" style={{ fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tx(s.item)}</div><div className="tiny muted">{tx(s.qty)} · {tx('by')} {teamById(s.author)?.name.split(' ')[0]}</div></div>
              <Badge kind={s.status === 'overdue' ? 'danger' : 'warning'}>{tdate(s.deadline)}</Badge>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================ QUOTE REQUESTS ============================ */
function QuoteOfferModal({ request, onClose, onSave }) {
  const existing = (request.offers || []).find((o) => o.workshopId === CURRENT_WORKSHOP_ID);
  const [draft, setDraft] = useSt(() => ({
    price: existing?.price || '',
    eta: existing?.eta || 'Tomorrow · 10:00',
    note: existing?.note || '',
  }));
  const valid = Number(draft.price) > 0 && draft.eta.trim();
  return (
    <Modal title={existing ? tx('Update price offer') : tx('Send price offer')} sub={`${request.customer} · ${request.vehicle.make} ${request.vehicle.model}`} onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>{tx('Cancel')}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={() => onSave({ ...draft, price: Number(draft.price), eta: draft.eta.trim(), note: draft.note.trim() })}>
          {React.createElement(Icon.check, { size: 15, stroke: 2.6 })} {tx('Send offer')}
        </button>
      </>}>
      <div className="card" style={{ background: 'var(--surface-2)', boxShadow: 'none', padding: '12px 14px', marginBottom: 14 }}>
        <VehicleCell v={request.vehicle} sub={request.customer} />
        <div className="tiny muted" style={{ marginTop: 10, lineHeight: 1.5 }}>{tx(request.description)}</div>
      </div>
      <div className="grid-2">
        <div className="field">
          <label>{tx('Your price')}</label>
          <div className="input-money">
            <span>zł</span>
            <input className="input" type="number" min="1" value={draft.price} onChange={(e) => setDraft({ ...draft, price: e.target.value })} autoFocus />
          </div>
        </div>
        <div className="field">
          <label>{tx('Earliest slot')}</label>
          <select className="select" value={draft.eta} onChange={(e) => setDraft({ ...draft, eta: e.target.value })}>
            {['Today · 16:00', 'Tomorrow · 09:30', 'Tomorrow · 10:00', 'Tomorrow · 12:00', 'In 2 days · 09:00'].map((x) => <option key={x} value={x}>{tdate(x)}</option>)}
          </select>
        </div>
      </div>
      <div className="field" style={{ marginBottom: 0 }}>
        <label>{tx('Message to customer')}</label>
        <textarea className="textarea" value={draft.note} onChange={(e) => setDraft({ ...draft, note: e.target.value })} placeholder={tx('What is included in the price?')} />
      </div>
    </Modal>
  );
}

function QuoteRequestCard({ request, onOffer }) {
  const offers = [...(request.offers || [])].sort((a, b) => a.price - b.price);
  const mine = offers.find((o) => o.workshopId === CURRENT_WORKSHOP_ID);
  const best = offers[0];
  const position = mine ? offers.findIndex((o) => o.workshopId === CURRENT_WORKSHOP_ID) + 1 : null;
  return (
    <div className="card">
      <div className="card-pad">
        <div className="between" style={{ alignItems: 'flex-start', gap: 16 }}>
          <div className="row" style={{ gap: 12, alignItems: 'flex-start' }}>
            <Avatar name={request.customer} size={40} />
            <div>
              <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
                <span className="strong">{request.customer}</span>
                <Badge kind="accent">{tx('Quote request')}</Badge>
                <Badge kind="outline">{request.location}</Badge>
              </div>
              <div className="tiny muted" style={{ marginTop: 3 }}>{request.phone} · {tx('created')} {tdate(request.created)} · {request.id}</div>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="tiny muted">{tx('Best price')}</div>
            <div className="mono strong" style={{ fontSize: 18 }}>{best ? zl(best.price) : '—'}</div>
          </div>
        </div>

        <div className="grid-2" style={{ marginTop: 14, gap: 12 }}>
          <div className="card" style={{ background: 'var(--surface-2)', padding: '11px 13px', boxShadow: 'none' }}>
            <div className="tiny muted" style={{ marginBottom: 6 }}>{tx('Vehicle')}</div>
            <VehicleCell v={request.vehicle} />
          </div>
          <div className="card" style={{ background: 'var(--surface-2)', padding: '11px 13px', boxShadow: 'none' }}>
            <div className="tiny muted" style={{ marginBottom: 6 }}>{tx('Customer request')}</div>
            <div className="strong sec">{tx(request.title)}</div>
            <div className="tiny muted" style={{ marginTop: 4, lineHeight: 1.45 }}>{tx(request.description)}</div>
          </div>
        </div>

        <div className="card" style={{ marginTop: 14, boxShadow: 'none', borderColor: 'var(--border)' }}>
          <table className="tbl">
            <thead><tr><th>{tx('Workshop')}</th><th>{tx('Rating')}</th><th>{tx('Slot')}</th><th>{tx('Note')}</th><th style={{ textAlign: 'right' }}>{tx('Price')}</th></tr></thead>
            <tbody>
              {offers.map((o) => (
                <tr key={o.workshopId} style={o.workshopId === CURRENT_WORKSHOP_ID ? { background: 'var(--accent-soft)' } : null}>
                  <td><div className="strong sec">{o.workshopName}{o.workshopId === CURRENT_WORKSHOP_ID ? ` · ${tx('you')}` : ''}</div><div className="tiny muted">{tx(o.updated)}</div></td>
                  <td><span className="row tiny" style={{ gap: 5 }}>{React.createElement(Icon.star, { size: 13, fill: 'currentColor', style: { color: 'var(--warning)' } })}<b>{o.rating}</b><span className="muted">({o.reviews})</span></span></td>
                  <td className="muted">{tdate(o.eta)}</td>
                  <td className="muted" style={{ maxWidth: 280 }}>{tx(o.note)}</td>
                  <td className="num strong">{zl(o.price)}</td>
                </tr>
              ))}
              {offers.length === 0 && <tr><td colSpan="5" className="muted">{tx('No offers yet')}</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
      <div className="card-ft" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        {mine ? <Badge kind={position === 1 ? 'success' : 'neutral'} pip>{position === 1 ? tx('You are the lowest offer') : fmt('Your offer is #{n} by price', { n: position })}</Badge> : <Badge kind="warning" pip>{tx('You have not offered yet')}</Badge>}
        <span className="spacer" />
        <button className="btn btn-primary" onClick={() => onOffer(request)}>
          {React.createElement(Icon.tag, { size: 15 })} {mine ? tx('Update offer') : tx('Offer price')}
        </button>
      </div>
    </div>
  );
}

function QuoteRequestsView() {
  const [requests, setRequests] = useStoredState('ac.quoteRequests', QUOTE_REQUESTS);
  const [editing, setEditing] = useSt(null);
  const open = requests.filter((r) => r.status === 'open');
  const myOffers = open.filter((r) => (r.offers || []).some((o) => o.workshopId === CURRENT_WORKSHOP_ID)).length;
  const saveOffer = async (draft) => {
    const apiOffer = editing ? await AutoCareAPI.proposeQuoteOffer(editing, draft).catch((e) => (console.warn('[AutoCareAPI] quote offer failed', e), null)) : null;
    const offer = apiOffer || {
      workshopId: CURRENT_WORKSHOP_ID,
      workshopName: SHOP.name,
      rating: SHOP.rating,
      reviews: SHOP.reviews,
      price: draft.price,
      eta: draft.eta,
      note: draft.note || tx('Price includes work and standard parts check'),
      updated: 'just now',
    };
    setRequests((items) => items.map((item) => {
      if (item.id !== editing.id) return item;
      const others = (item.offers || []).filter((o) => o.workshopId !== CURRENT_WORKSHOP_ID);
      return { ...item, offers: [...others, offer].sort((a, b) => a.price - b.price) };
    }));
    setEditing(null);
    toast(tx('Price offer sent to customer'), 'tag');
  };
  return (
    <div className="page view-fade" data-screen-label="Price requests">
      <div className="page-head">
        <div><div className="page-title">{tx('Price requests')}</div><div className="page-sub">{tx('Open customer orders where workshops compete by price and rating')}</div></div>
        <span className="spacer" />
        <Badge kind="neutral">{myOffers}/{open.length} {tx('answered')}</Badge>
      </div>
      <div className="grid-3" style={{ marginBottom: 18 }}>
        <Stat label={tx('Open requests')} icon="inbox" value={String(open.length)} accent />
        <Stat label={tx('Your offers')} icon="tag" value={String(myOffers)} delta={tx('visible to customers')} deltaDir="flat" />
        <Stat label={tx('Lowest active price')} icon="wallet" value={open.length ? zl(Math.min(...open.flatMap((r) => (r.offers || []).map((o) => o.price)))) : '—'} delta={tx('customer sort order')} deltaDir="flat" />
      </div>
      <div className="col" style={{ gap: 16 }}>
        {open.map((request) => <QuoteRequestCard key={request.id} request={request} onOffer={setEditing} />)}
        {open.length === 0 && <div className="empty">{tx('No open price requests')}</div>}
      </div>
      {editing && <QuoteOfferModal request={editing} onClose={() => setEditing(null)} onSave={saveOffer} />}
    </div>
  );
}

/* ============================ BOOKINGS ============================ */
function BookingCard({ b, onConfirm, onDecline, onPropose, confirmed }) {
  const total = b.services.reduce((a, id) => a + displayed(svc(id)?.net || 0), 0);
  return (
    <div className="card" style={{ opacity: confirmed ? 0.6 : 1, transition: 'opacity .3s' }}>
      <div className="card-pad" style={{ paddingBottom: 14 }}>
        <div className="between" style={{ alignItems: 'flex-start' }}>
          <div className="row" style={{ gap: 12 }}>
            <Avatar name={b.customer} size={40} />
            <div>
              <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}><span className="strong" style={{ whiteSpace: 'nowrap' }}>{b.customer}</span>
                {b.guest ? <Badge kind="outline">{tx('Guest')}</Badge> : <Badge kind="neutral">{tx('Registered')}</Badge>}
                {b.verified && <Badge kind="success">{React.createElement(Icon.check, { size: 11, stroke: 3 })} {tx('OTP verified')}</Badge>}</div>
              <div className="tiny muted" style={{ marginTop: 3 }}>{b.phone} · {tx('requested')} {tdate(b.requested)}</div>
            </div>
          </div>
          <span className="mono tiny muted">{b.id}</span>
        </div>

        <div className="grid-2" style={{ marginTop: 14, gap: 12 }}>
          <div className="card" style={{ background: 'var(--surface-2)', padding: '11px 13px', boxShadow: 'none' }}>
            <div className="tiny muted" style={{ marginBottom: 6 }}>{tx('Vehicle')}</div>
            <VehicleCell v={b.vehicle} />
          </div>
          <div className="card" style={{ background: 'var(--surface-2)', padding: '11px 13px', boxShadow: 'none' }}>
            <div className="tiny muted" style={{ marginBottom: 6 }}>{tx('Requested slot')}</div>
            <div className="row" style={{ gap: 8 }}>{React.createElement(Icon.calendar, { size: 16, style: { color: 'var(--text-2)' } })}<span className="strong sec" style={{ whiteSpace: 'nowrap' }}>{tdate(b.slot)}</span></div>
            <div className="row" style={{ gap: 8, marginTop: 8 }}><PayBadge method={b.method} /><span className="tiny muted">{b.method === 'cash' ? tx('pays on pickup') : tx('hold on confirm')}</span></div>
          </div>
        </div>

        <div className="between" style={{ marginTop: 14 }}>
          <div className="wrap">{b.services.map((id) => {
            const s = svc(id) || { name: id, net: 0 };
            return <Badge key={id} kind="outline">{tx(s.name)} · {zl(displayed(s.net))}</Badge>;
          })}</div>
          <div style={{ textAlign: 'right' }}><div className="tiny muted">{tx('Total from')}</div><div className="mono strong" style={{ fontSize: 17 }}>{zl(total)}</div></div>
        </div>
      </div>
      <div className="card-ft" style={{ display: 'flex', gap: 10 }}>
        {confirmed ? (
          <Badge kind="success" pip>{tx('Confirmed · work order created · customer notified')}</Badge>
        ) : (
          <>
            <button className="btn btn-primary" onClick={() => onConfirm(b.id)}>
              {React.createElement(Icon.check, { size: 15, stroke: 2.6 })} {tx('Confirm')} {b.method === 'card' ? tx('& place hold') : ''}
            </button>
            <button className="btn btn-outline" onClick={() => onPropose(b)}>{React.createElement(Icon.calendar, { size: 15 })} {tx('Propose new slot')}</button>
            <span className="spacer" />
            <button className="btn btn-danger sm" onClick={() => onDecline(b.id)}>{tx('Decline')}</button>
          </>
        )}
      </div>
    </div>
  );
}

function BookingsView({ go }) {
  const [done, setDone] = useStoredState('ac.bookings.done', {});
  const [tab, setTab] = useSt('awaiting');
  const [list, setList] = useStoredState('ac.bookings', BOOKINGS);
  const [slotBooking, setSlotBooking] = useSt(null);
  const confirm = async (id) => {
    const booking = list.find((b) => b.id === id);
    setDone((d) => ({ ...d, [id]: true }));
    if (booking) {
      const apiOrder = await AutoCareAPI.confirmBooking(booking).catch((e) => (console.warn('[AutoCareAPI] confirm failed', e), null));
      patchStored('ac.workOrders', WORK_ORDERS, (orders) => {
        if (orders.some((w) => w.bookingId === booking.id)) return orders;
        if (apiOrder) return [apiOrder, ...orders];
        const max = orders.reduce((m, w) => Math.max(m, Number(String(w.id).replace('WO-', '')) || 0), 1187);
        const baseNet = booking.services.reduce((sum, serviceId) => sum + (svc(serviceId)?.net || 0), 0);
        return [{
          id: 'WO-' + (max + 1),
          bookingId: booking.id,
          customer: booking.customer,
          vehicle: booking.vehicle,
          services: booking.services,
          assigned: ['u1'],
          status: 'accepted',
          method: booking.method,
          slot: booking.slot,
          opened: 'Today',
          ticketsCount: 0,
          ticketsApproved: 0,
          baseNet,
          ticketsNet: 0,
        }, ...orders];
      });
    }
    toast(tx('Booking confirmed — work order created'), 'checkCircle');
  };
  const decline = (id) => { setList((l) => l.filter((b) => b.id !== id)); toast(tx('Booking declined'), 'xCircle'); };
  const propose = (slot, note) => {
    setList((l) => l.map((b) => b.id === slotBooking.id ? { ...b, slot, proposedNote: note } : b));
    setSlotBooking(null);
    toast(tx('New slot proposed — customer notified'), 'calendar');
  };
  const visible = list.filter((b) => tab === 'all' ? true : tab === 'confirmed' ? done[b.id] : !done[b.id]);
  return (
    <div className="page view-fade" data-screen-label="Bookings">
      <div className="page-head">
        <div><div className="page-title">{tx('Requests')}</div><div className="page-sub">{tx('New bookings waiting for your confirmation')}</div></div>
        <span className="spacer" />
        <div className="seg">
          <button className={tab === 'awaiting' ? 'on' : ''} onClick={() => setTab('awaiting')}>{tx('Awaiting')} · {list.filter((b) => !done[b.id]).length}</button>
          <button className={tab === 'confirmed' ? 'on' : ''} onClick={() => setTab('confirmed')}>{tx('Confirmed')}</button>
          <button className={tab === 'all' ? 'on' : ''} onClick={() => setTab('all')}>{tx('All')}</button>
        </div>
      </div>
      <div className="col" style={{ gap: 16 }}>
        {visible.map((b) => <BookingCard key={b.id} b={b} confirmed={done[b.id]} onConfirm={confirm} onDecline={decline} onPropose={setSlotBooking} />)}
        {visible.length === 0 && <div className="empty"><div className="ico">{React.createElement(Icon.inbox, { size: 36 })}</div>{tx('No pending requests.')}</div>}
      </div>
      {slotBooking && <ProposeSlotModal booking={slotBooking} onClose={() => setSlotBooking(null)} onSave={propose} />}
    </div>
  );
}

/* ========================= WORK ORDERS LIST ========================= */
function OrdersView({ go }) {
  const [orders] = useStoredState('ac.workOrders', WORK_ORDERS);
  const [filter, setFilter] = useSt('active');
  const [q, setQ] = useSt('');
  const [filterOpen, setFilterOpen] = useSt(false);
  const tabs = [{ k: 'active', l: 'Active' }, { k: 'ready', l: 'Ready' }, { k: 'closed', l: 'Closed' }, { k: 'all', l: 'All' }];
  const match = (w) => filter === 'all' ? true
    : filter === 'active' ? ['accepted', 'in_progress'].includes(w.status)
    : filter === 'ready' ? w.status === 'ready'
    : ['paid', 'closed'].includes(w.status);
  const rows = orders.filter(match).filter((w) => {
    const hay = `${w.id} ${w.customer} ${w.vehicle.make} ${w.vehicle.model} ${w.vehicle.plate}`.toLowerCase();
    return !q.trim() || hay.includes(q.trim().toLowerCase());
  });
  const total = (w) => {
    const base = w.id === HERO.id ? 520 : (w.baseNet ? displayed(w.baseNet) : 0);
    const tk = w.id === HERO.id ? 0 : (w.ticketsNet ? displayed(w.ticketsNet) : 0);
    return base + tk;
  };
  return (
    <div className="page view-fade" data-screen-label="Work orders">
      <div className="page-head">
        <div><div className="page-title">{tx('Work orders')}</div><div className="page-sub">{tx('Every job in progress across the shop')}</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={q} onChange={(e) => setQ(e.target.value)} placeholder={tx('Search')} />
        </div>
        <button className="btn btn-outline" onClick={() => setFilterOpen(true)}>{React.createElement(Icon.filter, { size: 15 })} {tx('Filter')}</button>
      </div>
      <div className="seg" style={{ marginBottom: 16 }}>
        {tabs.map((t) => <button key={t.k} className={filter === t.k ? 'on' : ''} onClick={() => setFilter(t.k)}>{tx(t.l)}</button>)}
      </div>
      <div className="card">
        <table className="tbl">
          <thead><tr>
            <th>{tx('Vehicle / customer')}</th><th>{tx('Order')}</th><th>{tx('Status')}</th><th>{tx('Assigned')}</th><th>{tx('Tickets')}</th><th>{tx('Payment')}</th><th style={{ textAlign: 'right' }}>{tx('Total')}</th><th></th>
          </tr></thead>
          <tbody>
            {rows.map((w) => (
              <tr className="clickable" key={w.id} onClick={() => go('workorder', w.id)}>
                <td><VehicleCell v={w.vehicle} sub={w.customer} /></td>
                <td><span className="mono tiny muted2">{w.id}</span><div className="tiny muted">{tdate(w.slot)}</div></td>
                <td><StatusBadge status={w.status} /></td>
                <td><div className="row" style={{ gap: -6 }}>{(w.assigned || []).map((id, i) => (
                  <span key={id} style={{ marginLeft: i ? -8 : 0, border: '2px solid var(--surface)', borderRadius: '50%' }}><Avatar name={teamById(id)?.name} size={26} /></span>
                ))}</div></td>
                <td>{(w.id === HERO.id || w.ticketsCount) ? <Badge kind={w.id === HERO.id ? 'accent' : 'neutral'}>{w.id === HERO.id ? '3 · 2 ✓' : `${w.ticketsCount || 0} · ${w.ticketsApproved || 0} ✓`}</Badge> : <span className="muted tiny">—</span>}</td>
                <td><PayBadge method={w.method} /></td>
                <td className="num strong">{zl(total(w))}</td>
                <td>{React.createElement(Icon.chevR, { size: 16, style: { color: 'var(--text-3)' } })}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {filterOpen && (
        <Modal title={tx('Filter')} sub={tx('Select work order status')} onClose={() => setFilterOpen(false)}
          footer={<button className="btn btn-primary" onClick={() => setFilterOpen(false)}>{tx('Done')}</button>}>
          <div className="pickgrid">
            {tabs.map((t) => <button key={t.k} className={`pickchip ${filter === t.k ? 'on' : ''}`} onClick={() => setFilter(t.k)}>{filter === t.k && React.createElement(Icon.check, { size: 14, stroke: 2.8 })}{tx(t.l)}</button>)}
          </div>
        </Modal>
      )}
    </div>
  );
}

Object.assign(window, { OverviewView, BookingsView, OrdersView });
