// screen-orders.jsx — list, detail (standard/custom), new order

function OrdersList({ orders, onOpen, onNew, search, setSearch, filter, setFilter, dateFilter, setDateFilter, currentUser, pendingOrders = 0, onAcceptPending }) {
  const counts = React.useMemo(() => {
    const c = { all: 0, pending: 0, in_progress: 0, ready: 0, delivered: 0, cancelled: 0, custom: 0, standard: 0, baklava: 0, tepsi_unreturned: 0 };
    orders.forEach(o => {
      c.all++; c[o.status]++;
      if (c[o.type] !== undefined) c[o.type]++;
      if (o.status !== 'cancelled' &&
          o.baklava_data?.sold_as === 'tepsi' &&
          o.baklava_data?.tepsi_owner === 'ours' &&
          !o.baklava_data?.tepsi_returned) c.tepsi_unreturned++;
    });
    return c;
  }, [orders]);

  const TYPE_FILTERS = ['custom', 'standard', 'baklava', 'tepsi_unreturned'];
  const filtered = orders.filter(o => {
    if (filter === 'tepsi_unreturned') {
      return o.status !== 'cancelled' &&
             o.baklava_data?.sold_as === 'tepsi' &&
             o.baklava_data?.tepsi_owner === 'ours' &&
             !o.baklava_data?.tepsi_returned;
    }
    if (!TYPE_FILTERS.includes(filter) && filter !== 'all' && o.status !== filter) return false;
    if (['custom', 'standard', 'baklava'].includes(filter) && o.type !== filter) return false;
    if (dateFilter !== 'all') {
      const due = window.relativeDay(o.due_date);
      if (dateFilter === 'today' && due !== 'Sot') return false;
      if (dateFilter === 'week') {
        const diff = (new Date(o.due_date) - window.today) / 86400000;
        if (diff < 0 || diff > 7) return false;
      }
      if (dateFilter === 'past' && new Date(o.due_date) >= window.today) return false;
    }
    if (search) {
      const s = search.toLowerCase();
      if (!o.customer_name.toLowerCase().includes(s) && !(o.flavour || '').toLowerCase().includes(s) && !o.id.toLowerCase().includes(s)) return false;
    }
    return true;
  });

  // Group by due-date bucket
  const today = filtered.filter(o => window.relativeDay(o.due_date) === 'Sot');
  const tomorrow = filtered.filter(o => window.relativeDay(o.due_date) === 'Nesër');
  const upcoming = filtered.filter(o => {
    const d = (new Date(o.due_date) - window.today) / 86400000;
    return d > 1 && d <= 14;
  });
  const past = filtered.filter(o => (new Date(o.due_date) - window.today) / 86400000 < 0);
  const later = filtered.filter(o => (new Date(o.due_date) - window.today) / 86400000 > 14);

  const groups = [
    { label: 'Sot', tag: 'urgent', rows: today },
    { label: 'Nesër', tag: 'soon', rows: tomorrow },
    { label: 'Kjo javë dhe tjetra', tag: null, rows: upcoming },
    { label: 'Më vonë', tag: null, rows: later },
    { label: 'Të kaluara', tag: null, rows: past },
  ].filter(g => g.rows.length);

  return (
    <div>
      {/* New-order banner */}
      {pendingOrders > 0 && (
        <div onClick={onAcceptPending} style={{
          position: 'sticky', top: 0, zIndex: 20,
          marginBottom: 16,
          background: 'var(--ink)', color: 'var(--cream)',
          borderRadius: 12, padding: '12px 18px',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          cursor: 'pointer', userSelect: 'none',
          boxShadow: '0 4px 20px -4px rgba(59,31,10,0.35)',
          animation: 'slideup 240ms cubic-bezier(0.2,0.9,0.3,1)',
        }}>
          <IconBell size={16} color="var(--cream)" />
          <span style={{ fontWeight: 600, fontSize: 14 }}>
            {pendingOrders === 1 ? '1 porosi e re' : `${pendingOrders} porosi të reja`}
          </span>
          <span style={{ opacity: 0.65, fontSize: 13 }}>· Kliko për të rifreskuar</span>
          <IconRefresh size={14} color="var(--cream)" style={{ opacity: 0.65 }} />
        </div>
      )}

      {/* search + filters */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 220 }}>
          <input
            className="input"
            placeholder="Kërko porosi, klientë, shije…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            style={{ paddingLeft: 40 }}
          />
          <div style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', display: 'inline-flex' }}>
            <IconSearch size={16} color="var(--ink-mute)" />
          </div>
        </div>
        <button className="btn" onClick={onNew}>
          <IconPlus size={18} color="var(--cream)" />Porosi e re
        </button>
      </div>

      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4, marginBottom: 20, scrollbarWidth: 'none' }}>
        <FilterChip label="Të gjitha" count={counts.all} active={filter === 'all'} onClick={() => setFilter('all')} />
        <FilterChip label="Në pritje" count={counts.pending} active={filter === 'pending'} onClick={() => setFilter('pending')} />
        <FilterChip label="Në proces" count={counts.in_progress} active={filter === 'in_progress'} onClick={() => setFilter('in_progress')} />
        <FilterChip label="Gati" count={counts.ready} active={filter === 'ready'} onClick={() => setFilter('ready')} />
        <FilterChip label="Dorëzuar" count={counts.delivered} active={filter === 'delivered'} onClick={() => setFilter('delivered')} />
        <FilterChip label="Standard" count={counts.standard} active={filter === 'standard'} onClick={() => setFilter('standard')} />
        <FilterChip label="I personalizuar" count={counts.custom} active={filter === 'custom'} onClick={() => setFilter('custom')} />
        <FilterChip label="Bakllava" count={counts.baklava} active={filter === 'baklava'} onClick={() => setFilter('baklava')} />
        {counts.tepsi_unreturned > 0 && (
          <FilterChip label="Tepsi pa kthyer" count={counts.tepsi_unreturned} active={filter === 'tepsi_unreturned'} onClick={() => setFilter('tepsi_unreturned')} accent="var(--amber)" />
        )}
      </div>

      <div style={{ display: 'flex', gap: 8, marginBottom: 24, alignItems: 'center', flexWrap: 'wrap' }}>
        <span className="muted" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>Dorëzim</span>
        {[
          ['all', 'Gjithmonë'],
          ['today', 'Sot'],
          ['week', '7 ditët e ardhshme'],
          ['past', 'Të kaluara'],
        ].map(([v, l]) => (
          <button key={v} className={`chip ${dateFilter === v ? 'active' : ''}`}
            style={{ height: 30, fontSize: 12.5 }} onClick={() => setDateFilter(v)}>
            {l}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="card" style={{ textAlign: 'center', padding: 40 }}>
          <div className="display" style={{ fontSize: 22, marginBottom: 6 }}>Asnjë porosi nuk përputhet</div>
          <p className="muted" style={{ margin: 0 }}>Provoni të hiqni filtrat ose kërkimin.</p>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
          {groups.map(g => (
            <div key={g.label}>
              <div style={{
                display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12,
              }}>
                <h2 className="display" style={{ fontSize: 20, fontWeight: 600, margin: 0, letterSpacing: '-0.01em' }}>{g.label}</h2>
                <span className="muted" style={{ fontSize: 12, fontWeight: 500 }}>{g.rows.length} {g.rows.length === 1 ? 'porosi' : 'porosi'}</span>
                {g.tag === 'urgent' && (
                  <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--rose)' }}>
                    Piqni sot
                  </span>
                )}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(min(100%, 340px), 1fr))', gap: 12 }}>
                {g.rows.map(o => <OrderCard key={o.id} order={o} onClick={() => onOpen(o.id)} currentUser={currentUser} />)}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── ORDERS STATS ─────────────────────────────────────────────────────────

function StatsScreen({ orders }) {
  const stats = React.useMemo(() => {
    const ACTIVE = new Set(['pending', 'in_progress', 'dough_ready', 'ready']);
    const INWORK = new Set(['pending', 'in_progress', 'dough_ready']);

    let bak_tepsi_todo = 0, bak_kg_todo = 0;
    let bak_tepsi_ready = 0, bak_kg_ready = 0;
    let bak_today = 0, bak_tomorrow = 0;
    let bak_tepsi_unreturned = 0;

    let cake_todo = 0, cake_ready = 0, cake_active = 0;
    let cake_today = 0, cake_tomorrow = 0, cake_week = 0;
    let cake_custom = 0, cake_standard = 0;

    orders.forEach(o => {
      const isActive = ACTIVE.has(o.status);
      const isInWork = INWORK.has(o.status);
      const due = window.relativeDay(o.due_date);
      const daysAway = (new Date(o.due_date) - window.today) / 86400000;

      if (o.type === 'baklava') {
        if (isActive) {
          const qty = o.baklava_data?.quantity || 0;
          const isTepsi = o.baklava_data?.sold_as === 'tepsi';
          if (isInWork) {
            if (isTepsi) bak_tepsi_todo += qty; else bak_kg_todo += qty;
          } else if (o.status === 'ready') {
            if (isTepsi) bak_tepsi_ready += qty; else bak_kg_ready += qty;
          }
          if (due === 'Sot') bak_today++;
          else if (due === 'Nesër') bak_tomorrow++;
        }
        // Count unreturned our-tepsi across ALL non-cancelled orders
        if (o.status !== 'cancelled' &&
            o.baklava_data?.sold_as === 'tepsi' &&
            o.baklava_data?.tepsi_owner === 'ours' &&
            !o.baklava_data?.tepsi_returned) {
          bak_tepsi_unreturned += o.baklava_data?.quantity || 0;
        }
      } else {
        if (isActive) {
          cake_active++;
          if (isInWork) cake_todo++;
          else if (o.status === 'ready') cake_ready++;
          if (due === 'Sot') cake_today++;
          else if (due === 'Nesër') cake_tomorrow++;
          else if (daysAway > 1 && daysAway <= 7) cake_week++;
          if (o.type === 'custom') cake_custom++;
          else cake_standard++;
        }
      }
    });

    return {
      bak_tepsi_todo, bak_kg_todo, bak_tepsi_ready, bak_kg_ready,
      bak_today, bak_tomorrow, bak_tepsi_unreturned,
      cake_todo, cake_ready, cake_active, cake_today, cake_tomorrow, cake_week,
      cake_custom, cake_standard,
    };
  }, [orders]);

  const hasBaklava = stats.bak_tepsi_todo > 0 || stats.bak_kg_todo > 0 || stats.bak_tepsi_ready > 0 || stats.bak_kg_ready > 0;
  const hasCakes = stats.cake_active > 0;
  const fmtKg = (v) => v % 1 === 0 ? String(v) : v.toFixed(1);

  if (!hasBaklava && !hasCakes) return (
    <div style={{ textAlign: 'center', padding: '80px 20px' }}>
      <IconBarChart size={44} color="var(--ink-mute)" />
      <p className="muted" style={{ marginTop: 14, fontSize: 15 }}>Nuk ka porosi aktive</p>
    </div>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

      {hasBaklava && (
        <div className="card" style={{ padding: '20px 22px', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: 'var(--amber)' }} />
          <h2 className="display" style={{ margin: '0 0 18px', fontSize: 17, fontWeight: 700, color: 'var(--amber)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <IconCake size={16} color="var(--amber)" /> Bakllava
          </h2>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 12 }}>
            <StatCard label="Tepsi për të bërë" value={stats.bak_tepsi_todo} accent="var(--amber)" sub="pending / në punë" />
            <StatCard label="Kg për të bërë" value={fmtKg(stats.bak_kg_todo)} accent="var(--amber)" sub="pending / në punë" />
            <StatCard label="Tepsi gati" value={stats.bak_tepsi_ready} accent="var(--green)" sub="gati për dorëzim" />
            <StatCard label="Kg gati" value={fmtKg(stats.bak_kg_ready)} accent="var(--green)" sub="gati për dorëzim" />
          </div>

          {stats.bak_tepsi_unreturned > 0 && (
            <div style={{ marginTop: 14, padding: '12px 14px', background: 'rgba(216,147,49,0.08)', borderRadius: 10, border: '1px solid rgba(216,147,49,0.25)', display: 'flex', alignItems: 'center', gap: 10 }}>
              <IconClock size={16} color="var(--amber)" />
              <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>
                <strong style={{ color: 'var(--amber)' }}>{stats.bak_tepsi_unreturned}</strong> tepsi të tonat ende nuk janë kthyer
              </span>
            </div>
          )}

          {(stats.bak_today > 0 || stats.bak_tomorrow > 0) && (
            <div style={{ marginTop: 16, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {stats.bak_today > 0 && (
                <div style={{ padding: '8px 14px', background: 'rgba(140,46,46,0.08)', borderRadius: 8, border: '1px solid rgba(140,46,46,0.18)' }}>
                  <span style={{ fontWeight: 700, color: '#8c2e2e', fontSize: 15 }}>{stats.bak_today}</span>
                  <span style={{ fontSize: 12, color: 'var(--ink-2)', marginLeft: 6 }}>porosi dorëzohen sot</span>
                </div>
              )}
              {stats.bak_tomorrow > 0 && (
                <div style={{ padding: '8px 14px', background: 'rgba(216,147,49,0.08)', borderRadius: 8, border: '1px solid rgba(216,147,49,0.2)' }}>
                  <span style={{ fontWeight: 700, color: 'var(--amber)', fontSize: 15 }}>{stats.bak_tomorrow}</span>
                  <span style={{ fontSize: 12, color: 'var(--ink-2)', marginLeft: 6 }}>porosi dorëzohen nesër</span>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {hasCakes && (
        <div className="card" style={{ padding: '20px 22px', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: 'var(--rose)' }} />
          <h2 className="display" style={{ margin: '0 0 18px', fontSize: 17, fontWeight: 700, color: 'var(--rose)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <IconCake size={16} color="var(--rose)" /> Torta
          </h2>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 12 }}>
            <StatCard label="Gjithsej aktive" value={stats.cake_active} accent="var(--ink)" sub="të gjitha statuset" />
            <StatCard label="Për të bërë" value={stats.cake_todo} accent="var(--rose)" sub="pending / në punë" />
            <StatCard label="Gati" value={stats.cake_ready} accent="var(--green)" sub="gati për dorëzim" />
          </div>

          {(stats.cake_today > 0 || stats.cake_tomorrow > 0 || stats.cake_week > 0) && (
            <div style={{ marginTop: 16, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {stats.cake_today > 0 && (
                <div style={{ padding: '8px 14px', background: 'rgba(140,46,46,0.08)', borderRadius: 8, border: '1px solid rgba(140,46,46,0.18)' }}>
                  <span style={{ fontWeight: 700, color: '#8c2e2e', fontSize: 15 }}>{stats.cake_today}</span>
                  <span style={{ fontSize: 12, color: 'var(--ink-2)', marginLeft: 6 }}>dorëzohen sot</span>
                </div>
              )}
              {stats.cake_tomorrow > 0 && (
                <div style={{ padding: '8px 14px', background: 'rgba(212,96,122,0.08)', borderRadius: 8, border: '1px solid rgba(212,96,122,0.2)' }}>
                  <span style={{ fontWeight: 700, color: 'var(--rose)', fontSize: 15 }}>{stats.cake_tomorrow}</span>
                  <span style={{ fontSize: 12, color: 'var(--ink-2)', marginLeft: 6 }}>dorëzohen nesër</span>
                </div>
              )}
              {stats.cake_week > 0 && (
                <div style={{ padding: '8px 14px', background: 'var(--cream-2)', borderRadius: 8, border: '1px solid var(--line)' }}>
                  <span style={{ fontWeight: 700, color: 'var(--ink-2)', fontSize: 15 }}>{stats.cake_week}</span>
                  <span style={{ fontSize: 12, color: 'var(--ink-2)', marginLeft: 6 }}>kjo javë</span>
                </div>
              )}
            </div>
          )}

          {(stats.cake_custom > 0 || stats.cake_standard > 0) && (
            <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line)', display: 'flex', gap: 18 }}>
              <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>
                <span style={{ fontWeight: 700, color: 'var(--rose)' }}>{stats.cake_custom}</span> personalizuara
              </span>
              <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>
                <span style={{ fontWeight: 700 }}>{stats.cake_standard}</span> standarde
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function StatCard({ label, value, accent, sub }) {
  return (
    <div style={{ padding: '14px 16px', background: 'var(--cream-2)', borderRadius: 10 }}>
      <div className="display tabular" style={{ fontSize: 34, fontWeight: 700, lineHeight: 1, color: accent }}>{value}</div>
      <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)', marginTop: 5 }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

// ── ORDER DETAIL ──────────────────────────────────────────────────────────

function OrderDetail({ order, currentUser, onBack, onUpdate, onDelete, addToast, fridgeConfig = { multiFridge: false, fridges: [] }, flavours = [], pricingConfig, baklavaPricing = { tepsi: 40, kg: 10 } }) {
  const isOwner = currentUser.role === 'owner';
  const [editing, setEditing] = React.useState(false);
  const [confirmCancel, setConfirmCancel] = React.useState(false);
  const [confirmDelete, setConfirmDelete] = React.useState(false);
  const [editingPrice, setEditingPrice] = React.useState(false);
  const [editingNotes, setEditingNotes] = React.useState(false);
  const [tempPrice, setTempPrice] = React.useState(order.payment?.total_price ?? '');
  const [tempNotes, setTempNotes] = React.useState(order.notes || '');

  // Custom-order AI state
  const [predicting, setPredicting] = React.useState(false);
  const [correcting, setCorrecting] = React.useState(false);
  const [correctValue, setCorrectValue] = React.useState('');

  const [lightbox, setLightbox] = React.useState(false);
  const API_BASE = window.location.hostname === 'localhost' ? 'http://localhost:4000' : '';
  const imgSrc = order.image_url ? `${API_BASE}${order.image_url}` : null;

  const downloadImage = async () => {
    try {
      const res = await fetch(imgSrc);
      const blob = await res.blob();
      const ext = imgSrc.split('.').pop().split('?')[0] || 'jpg';
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `pasticeria-${order.id.slice(-4)}.${ext}`;
      a.click();
      URL.revokeObjectURL(url);
    } catch { window.open(imgSrc, '_blank'); }
  };

  React.useEffect(() => {
    if (!lightbox) return;
    const onKey = (e) => { if (e.key === 'Escape') setLightbox(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [lightbox]);

  const statusOrder = window.getStatusOrder(order.type);
  const statusLabels = window.getStatusLabels(order.type);
  const statusIdx = statusOrder.indexOf(order.status);
  const canAdvance = order.status !== 'delivered' && order.status !== 'cancelled';
  const nextStatus = canAdvance ? statusOrder[statusIdx + 1] : null;

  const advanceStatus = () => {
    if (!nextStatus) return;
    onUpdate(order.id, { status: nextStatus });
    addToast(`Porosia u shënua si ${statusLabels[nextStatus]}`);
  };

  const savePrice = () => {
    const n = parseFloat(tempPrice);
    if (Number.isNaN(n)) return;
    onUpdate(order.id, { payment: { ...order.payment, total_price: n } });
    setEditingPrice(false);
    addToast('Çmimi total u përditësua');
  };

  const recordDeposit = () => {
    const amount = prompt('Shuma e depozitës (€):', '20');
    if (amount === null) return;
    const n = parseFloat(amount);
    if (Number.isNaN(n)) return;
    onUpdate(order.id, { payment: { ...order.payment, deposit_amount: n, deposit_paid_at: new Date().toISOString() } });
    addToast('Depozita u regjistrua');
  };

  const markFullyPaid = () => {
    onUpdate(order.id, { payment: { ...order.payment, fully_paid_at: new Date().toISOString() } });
    addToast('Shënuar si paguar plotësisht');
  };

  const startPredict = () => {
    setPredicting(true);
    setTimeout(() => {
      setPredicting(false);
      const samples = [
        { predicted_price: 92.5, confidence: 'medium', conf_score: 0.74, similar_count: 8 },
        { predicted_price: 78.0, confidence: 'high', conf_score: 0.88, similar_count: 12 },
        { predicted_price: 58.0, confidence: 'low', conf_score: 0.52, similar_count: 2 },
      ];
      const sample = samples[Math.floor(Math.random() * samples.length)];
      onUpdate(order.id, { ai: sample });
      addToast('Parashikimi u gjenerua');
    }, 1800);
  };

  const submitCorrection = () => {
    const n = parseFloat(correctValue);
    if (Number.isNaN(n)) return;
    onUpdate(order.id, {
      payment: { ...order.payment, total_price: n },
      manually_priced: true,
      _correction: { predicted: order.ai?.predicted_price, correct: n },
    });
    setCorrecting(false);
    setCorrectValue('');
    addToast('Çmimi u korrigjua. Do ristërvitet sonte.');
  };

  if (editing) {
    return (
      <EditOrderForm
        order={order}
        flavours={flavours}
        pricingConfig={pricingConfig}
        baklavaPricing={baklavaPricing}
        onSave={(patch) => {
          onUpdate(order.id, patch);
          setEditing(false);
          addToast('Porosia u përditësua');
        }}
        onCancel={() => setEditing(false)}
        addToast={addToast}
      />
    );
  }

  return (
    <div className="fade-in" style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 900 }}>
      <button onClick={onBack} className="chip" style={{ alignSelf: 'flex-start' }}>
        <IconArrowLeft size={14} /> Kthehu te porositë
      </button>

      {/* Hero */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 0 }} className="order-hero">
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {imgSrc ? (
            <div style={{ aspectRatio: '4/3', background: 'var(--cream-2)', position: 'relative' }}>
              <img
                src={imgSrc}
                onClick={() => setLightbox(true)}
                style={{ width: '100%', height: '100%', objectFit: 'cover', cursor: 'zoom-in', display: 'block' }}
                title="Kliko për të zmadhuar"
              />
              {/* Badges */}
              <div style={{ position: 'absolute', top: 14, left: 14, display: 'flex', gap: 6 }}>
                <StatusBadge status={order.status} size="lg" orderType={order.type} />
                {order.type === 'custom' && (
                  <span className="badge" style={{ background: 'rgba(212, 96, 122, 0.15)', color: 'var(--rose)', fontSize: 13, padding: '6px 14px' }}>
                    <IconSparkle size={12} color="var(--rose)" /> Dizajn i personalizuar
                  </span>
                )}
                {order.manually_priced && (
                  <span className="badge" style={{ background: 'white', color: 'var(--ink-2)', fontSize: 13, padding: '6px 14px', border: '1px solid var(--line)' }}>
                    Çmim manual
                  </span>
                )}
              </div>
              {/* Image action buttons */}
              <div style={{ position: 'absolute', top: 10, right: 10, display: 'flex', gap: 6 }}>
                <button onClick={downloadImage} title="Shkarko imazhin"
                  style={{ width: 34, height: 34, borderRadius: 8, border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)' }}>
                  <IconDownload size={16} color="white" />
                </button>
                <button onClick={() => setLightbox(true)} title="Hap në ekran të plotë"
                  style={{ width: 34, height: 34, borderRadius: 8, border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)' }}>
                  <IconExpand size={16} color="white" />
                </button>
              </div>
            </div>
            ) : null}
          </div>
          <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div>
              <div className="muted" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 4 }}>
                Porosia #{order.id.slice(-4)} · {order.type === 'standard' ? 'standard' : order.type === 'baklava' ? 'bakllava' : 'i personalizuar'}
              </div>
              <h1 className="display" style={{ margin: 0, fontSize: 34, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1.05 }}>
                {order.customer_name}
              </h1>
              <div style={{ marginTop: 8 }}>
                <ContactDisplay contact={order.customer_contact} />
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: 16, padding: '12px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
              <div>
                <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Dorëzim</div>
                <div className="display" style={{ fontSize: 20, fontWeight: 600 }}>{window.relativeDay(order.due_date)}</div>
                <div className="muted" style={{ fontSize: 12 }}>{window.formatDate(order.due_date)}</div>
              </div>
              <div>
                <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>
                  {order.type === 'standard' ? 'Shija' : order.type === 'baklava' ? 'Bakllava' : 'Lloji'}
                </div>
                {order.type === 'standard' ? (
                  <>
                    <div className="display" style={{ fontSize: 20, fontWeight: 600 }}>{order.flavour}</div>
                    <div className="muted" style={{ fontSize: 12 }}>{order.persons} persona</div>
                  </>
                ) : order.type === 'baklava' ? (
                  <>
                    <div className="display" style={{ fontSize: 20, fontWeight: 600 }}>
                      {order.baklava_data?.sold_as === 'tepsi'
                        ? `${order.baklava_data.quantity} tepsi`
                        : `${order.baklava_data?.quantity} kg`}
                    </div>
                    <div className="muted" style={{ fontSize: 12 }}>
                      {order.baklava_data?.sold_as === 'tepsi'
                        ? (order.baklava_data?.tepsi_owner === 'customer' ? 'Tepsi i klientit' : 'Tepsi jonë')
                        : 'Me kilogram'}
                    </div>
                  </>
                ) : (
                  <>
                    <div className="display" style={{ fontSize: 20, fontWeight: 600 }}>I personalizuar</div>
                    <div className="muted" style={{ fontSize: 12 }}>Çmim manual</div>
                  </>
                )}
              </div>
              <div>
                <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Madhësia</div>
                {order.diameter ? (
                  <>
                    <div className="display" style={{ fontSize: 18, fontWeight: 600, lineHeight: 1.3 }}>
                      <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)', display: 'block', marginBottom: 2 }}>Kati 1</span>
                      <span className="tabular">{order.diameter}</span>
                      <span style={{ fontSize: 13, fontWeight: 400, color: 'var(--ink-mute)', marginLeft: 2 }}>cm</span>
                      {order.variant ? <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--rose)', marginLeft: 6 }}>+{order.variant}</span> : null}
                    </div>
                    {order.flats && order.flats.map((f, i) => (
                      <div key={i} className="display" style={{ fontSize: 18, fontWeight: 600, lineHeight: 1.3, marginTop: 4 }}>
                        <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)', display: 'block', marginBottom: 2 }}>Kati {i + 2}</span>
                        <span className="tabular">{f.size}</span>
                        <span style={{ fontSize: 13, fontWeight: 400, color: 'var(--ink-mute)', marginLeft: 2 }}>cm</span>
                        {f.variant ? <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--rose)', marginLeft: 6 }}>+{f.variant}</span> : null}
                      </div>
                    ))}
                  </>
                ) : order.flats && order.flats.length > 0 ? (
                  <>
                    {order.flats.map((f, i) => (
                      <div key={i} className="display" style={{ fontSize: 18, fontWeight: 600, lineHeight: 1.3 }}>
                        <span className="tabular">{f.size}</span>
                        <span style={{ fontSize: 13, fontWeight: 400, color: 'var(--ink-mute)', marginLeft: 2 }}>cm</span>
                      </div>
                    ))}
                    <div className="muted" style={{ fontSize: 12 }}>Kate</div>
                  </>
                ) : (
                  <>
                    <div className="display" style={{ fontSize: 20, fontWeight: 600, color: 'var(--ink-mute)' }}>—</div>
                    <div className="muted" style={{ fontSize: 12 }}>E paspecifikuar</div>
                  </>
                )}
              </div>
            </div>

            {/* Status advance */}
            {canAdvance && (
              <button className="btn" onClick={advanceStatus}>
                <IconCheck size={18} color="var(--cream)" />
                Shëno si {statusLabels[nextStatus]}
              </button>
            )}
            {order.status === 'delivered' && (
              <div style={{ padding: '12px 16px', background: 'var(--green-soft)', borderRadius: 10, color: '#285d3f', display: 'flex', gap: 8, alignItems: 'center', fontSize: 14, fontWeight: 500 }}>
                <IconCircleCheck size={16} color="#285d3f" /> Dorëzuar. Punë e mirë!
              </div>
            )}
            {order.status === 'cancelled' && (
              <div style={{ padding: '12px 16px', background: 'var(--red-soft)', borderRadius: 10, color: '#8c2e2e', display: 'flex', gap: 8, alignItems: 'center', fontSize: 14, fontWeight: 500 }}>
                <IconX size={16} color="#8c2e2e" /> Kjo porosi u anulua.
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Tepsi return tracking */}
      {order.type === 'baklava' && order.baklava_data?.sold_as === 'tepsi' && order.baklava_data?.tepsi_owner === 'ours' && (
        <div className="card" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, flexShrink: 0, display: 'grid', placeItems: 'center',
              background: order.baklava_data?.tepsi_returned ? 'var(--green-soft)' : 'rgba(216,147,49,0.1)' }}>
              {order.baklava_data?.tepsi_returned
                ? <IconCircleCheck size={20} color="#285d3f" />
                : <IconClock size={20} color="var(--amber)" />}
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Kthimi i tepsiut</div>
              <div className="muted" style={{ fontSize: 12.5 }}>
                {order.baklava_data?.tepsi_returned
                  ? `${order.baklava_data.quantity} tepsi u kthye`
                  : `${order.baklava_data.quantity} tepsi ende nuk është kthyer`}
              </div>
            </div>
          </div>
          {!order.baklava_data?.tepsi_returned && (
            <button className="btn" onClick={() => {
              onUpdate(order.id, { baklava_data: { ...order.baklava_data, tepsi_returned: true } });
              addToast('Tepsi u shënua si i kthyer');
            }} style={{ background: 'var(--green)', borderColor: 'var(--green)', whiteSpace: 'nowrap' }}>
              <IconCheck size={15} color="white" /> Shëno si i kthyer
            </button>
          )}
        </div>
      )}

      {/* Fridge assignment — only shown when multi-fridge is enabled */}
      {fridgeConfig.multiFridge && (order.fridge || order.status === 'ready') && (
        <div className="card" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, flexShrink: 0, display: 'grid', placeItems: 'center',
              background: order.fridge ? 'rgba(75,148,143,0.12)' : 'var(--cream-2)', fontSize: 20 }}>
              ❄
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Frigorifer</div>
              <div className="muted" style={{ fontSize: 12.5 }}>
                {order.fridge ? `Caktuar te ${order.fridge}` : 'Nuk është caktuar frigorifer'}
              </div>
            </div>
          </div>
          {order.status === 'ready' && (
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {fridgeConfig.fridges.length === 0 ? (
                <span className="muted" style={{ fontSize: 13, fontStyle: 'italic' }}>
                  Asnjë frigorifer i konfiguruar. Shtoni nga cilësimet.
                </span>
              ) : fridgeConfig.fridges.map(name => (
                <button key={name} onClick={() => {
                  const next = order.fridge === name ? null : name;
                  onUpdate(order.id, { fridge: next });
                  addToast(next ? `Caktuar te ${name}` : 'Frigoriferi u hoq');
                }} style={{
                  padding: '0 14px', height: 36, borderRadius: 8, border: '1.5px solid',
                  fontWeight: 600, fontSize: 13, cursor: 'pointer', whiteSpace: 'nowrap',
                  borderColor: order.fridge === name ? 'var(--ink)' : 'var(--line-2)',
                  background: order.fridge === name ? 'var(--ink)' : 'transparent',
                  color: order.fridge === name ? 'var(--cream)' : 'var(--ink)',
                }}>
                  {name}
                </button>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Status timeline */}
      {order.status !== 'cancelled' && (
        <div className="card-warm">
          <SectionHeader title="Progresi" subtitle="Porosia kalon nëpër këto faza." />
          <div className="timeline">
            {statusOrder.map((s, i) => (
              <div key={s} className={`timeline-step ${i <= statusIdx ? 'active' : ''}`} />
            ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 12, color: 'var(--ink-mute)' }}>
            {statusOrder.map(s => (
              <span key={s} style={{ fontWeight: s === order.status ? 600 : 400, color: s === order.status ? 'var(--ink)' : 'var(--ink-mute)' }}>
                {statusLabels[s]}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* AI prediction (custom orders) */}
      {order.type === 'custom' && window.FEATURES.aiPricing && (
        <AIPredictionBlock
          order={order}
          predicting={predicting}
          startPredict={startPredict}
          correcting={correcting}
          setCorrecting={setCorrecting}
          correctValue={correctValue}
          setCorrectValue={setCorrectValue}
          submitCorrection={submitCorrection}
        />
      )}

      {/* Payment */}
      <div className="card">
        <SectionHeader
          title="Pagesa"
          subtitle={order.type === 'custom' && !order.payment?.total_price ? 'Vendosni çmimin përfundimtar pasi ta konfirmoni.' : 'Gjurmoni depozitën dhe pagesën finale.'}
          action={<PaymentBadge payment={order.payment} size="lg" />}
        />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 16, marginBottom: 16 }}>
          {/* Total */}
          <div style={{ padding: 16, background: 'var(--cream)', borderRadius: 10, border: '1px solid var(--line)' }}>
            <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Çmimi total</div>
            {editingPrice && isOwner ? (
              <div style={{ display: 'flex', gap: 6 }}>
                <input className="input" autoFocus type="number" step="0.01" value={tempPrice} onChange={(e) => setTempPrice(e.target.value)}
                       style={{ height: 40 }} />
                <button className="btn sm" onClick={savePrice} style={{ flexShrink: 0 }}><IconCheck size={14} color="var(--cream)" /></button>
              </div>
            ) : (
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span className="display tabular" style={{ fontSize: 28, fontWeight: 600 }}>
                  {window.formatEURP(order.payment?.total_price)}
                </span>
                {isOwner && (
                  <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => { setTempPrice(order.payment?.total_price ?? ''); setEditingPrice(true); }}>
                    <IconEdit size={14} />
                  </button>
                )}
              </div>
            )}
            {!isOwner && <span className="muted" style={{ fontSize: 11 }}>Vendosur nga pronari</span>}
          </div>
          <div style={{ padding: 16, background: 'var(--cream)', borderRadius: 10, border: '1px solid var(--line)' }}>
            <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Depozita</div>
            <div className="display tabular" style={{ fontSize: 28, fontWeight: 600 }}>
              {window.formatEURP(order.payment?.deposit_amount)}
            </div>
            <div className="muted" style={{ fontSize: 11 }}>{order.payment?.deposit_paid_at ? `Paguar ${window.relativeDay(order.payment.deposit_paid_at.slice(0, 10))}` : 'E papranuar'}</div>
          </div>
          <div style={{ padding: 16, background: 'var(--cream)', borderRadius: 10, border: '1px solid var(--line)' }}>
            <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Mbetur</div>
            <div className="display tabular" style={{ fontSize: 28, fontWeight: 600, color: order.payment?.fully_paid_at ? 'var(--green)' : 'var(--ink)' }}>
              {order.payment?.fully_paid_at ? '€0' : window.formatEURP(
                Math.max(0, (order.payment?.total_price || 0) - (order.payment?.deposit_amount || 0))
              )}
            </div>
            <div className="muted" style={{ fontSize: 11 }}>{order.payment?.fully_paid_at ? `Paguar plotësisht ${window.relativeDay(order.payment.fully_paid_at.slice(0, 10))}` : 'Paguhet në marrje'}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {!order.payment?.deposit_amount && (
            <button className="btn secondary" onClick={recordDeposit}>
              <IconEuro size={16} /> Regjistro depozitën
            </button>
          )}
          {!order.payment?.fully_paid_at && order.payment?.total_price && (
            <button className="btn green" onClick={markFullyPaid}>
              <IconCheck size={16} color="white" /> Shëno si paguar plotësisht
            </button>
          )}
        </div>
      </div>

      {/* Details */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
        {order.type === 'standard' && order.cake_text && (
          <div className="card">
            <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 8 }}>Teksti në tortë</div>
            <div className="serif-italic" style={{ fontSize: 22, fontWeight: 500, color: 'var(--rose)', lineHeight: 1.3 }}>
              "{order.cake_text}"
            </div>
          </div>
        )}
        <div className="card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Shënime</div>
            <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => { setTempNotes(order.notes || ''); setEditingNotes(true); }}>
              <IconEdit size={14} />
            </button>
          </div>
          {editingNotes ? (
            <>
              <textarea className="textarea" autoFocus value={tempNotes} onChange={(e) => setTempNotes(e.target.value)} />
              <div style={{ display: 'flex', gap: 8, marginTop: 8, justifyContent: 'flex-end' }}>
                <button className="btn secondary sm" onClick={() => setEditingNotes(false)}>Anulo</button>
                <button className="btn sm" onClick={() => { onUpdate(order.id, { notes: tempNotes }); setEditingNotes(false); addToast('Shënimet u ruajtën'); }}>Ruaj</button>
              </div>
            </>
          ) : (
            <div style={{ fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink-2)' }}>
              {order.notes || <span className="muted" style={{ fontStyle: 'italic' }}>Asnjë shënim akoma</span>}
            </div>
          )}
        </div>
      </div>

      {/* Photo upload on detail */}
      <div className="card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: order.image_url ? 12 : 0 }}>
          <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Foto e tortës</div>
          <label style={{ cursor: 'pointer' }}>
            <input type="file" accept="image/*" style={{ display: 'none' }}
              onChange={e => {
                const file = e.target.files[0];
                if (!file) return;
                window.api.uploadImage(file)
                  .then(({ url }) => { onUpdate(order.id, { image_url: url }); addToast('Foto u përditësua'); })
                  .catch(() => addToast('Ngarkimi i fotos dështoi'));
              }}
            />
            <span className="chip" style={{ height: 28, padding: '0 12px', fontSize: 12, cursor: 'pointer' }}>
              {order.image_url ? 'Zëvendëso foton' : 'Ngarko foto'}
            </span>
          </label>
        </div>
        {order.image_url ? (
          <img src={`${API_BASE}${order.image_url}`}
            style={{ width: '100%', maxHeight: 320, objectFit: 'cover', borderRadius: 10 }} />
        ) : (
          <div className="muted" style={{ fontSize: 13, fontStyle: 'italic' }}>Asnjë foto akoma</div>
        )}
      </div>

      {/* Footer actions */}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
        {isOwner && (
          <button className="btn secondary" onClick={() => setEditing(true)} style={{ marginRight: 'auto' }}>
            <IconEdit size={15} /> Ndrysho porosinë
          </button>
        )}
        {order.status !== 'cancelled' && order.status !== 'delivered' && (
          <button className="btn secondary" onClick={() => setConfirmCancel(true)}>
            Anulo porosinë
          </button>
        )}
        {isOwner && (
          <button className="btn danger" onClick={() => setConfirmDelete(true)}>
            <IconTrash size={14} color="var(--red)" /> Fshi porosinë
          </button>
        )}
      </div>

      <ConfirmDialog
        open={confirmCancel}
        title="Anulo porosinë?"
        body={`Kjo do të shënojë porosinë #${order.id.slice(-4)} si të anuluar. Klienti duhet njoftuar veçmas.`}
        confirmLabel="Po, anulo porosinë"
        danger
        onConfirm={() => { onUpdate(order.id, { status: 'cancelled' }); setConfirmCancel(false); addToast('Porosia u anulua'); }}
        onCancel={() => setConfirmCancel(false)}
      />
      <ConfirmDialog
        open={confirmDelete}
        title="Fshi porosinë?"
        body={`Porosia #${order.id.slice(-4)} për ${order.customer_name} do të fshihet përgjithmonë. Kjo nuk mund të zhbëhet.`}
        confirmLabel="Fshi përgjithmonë"
        danger
        onConfirm={() => { onDelete(order.id); addToast('Porosia u fshi'); }}
        onCancel={() => setConfirmDelete(false)}
      />

      {/* Lightbox */}
      {lightbox && imgSrc && (
        <div
          onClick={() => setLightbox(false)}
          style={{
            position: 'fixed', inset: 0, zIndex: 200,
            background: 'rgba(0,0,0,0.92)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'zoom-out',
          }}
        >
          <img
            src={imgSrc}
            onClick={(e) => e.stopPropagation()}
            style={{ maxWidth: '92vw', maxHeight: '92vh', objectFit: 'contain', borderRadius: 6, boxShadow: '0 24px 80px rgba(0,0,0,0.6)', cursor: 'default' }}
          />
          <div style={{ position: 'absolute', top: 16, right: 16, display: 'flex', gap: 8 }}>
            <button onClick={(e) => { e.stopPropagation(); downloadImage(); }} title="Shkarko"
              style={{ width: 40, height: 40, borderRadius: 10, border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: 'rgba(255,255,255,0.12)', backdropFilter: 'blur(8px)' }}>
              <IconDownload size={18} color="white" />
            </button>
            <button onClick={() => setLightbox(false)} title="Mbyll (Esc)"
              style={{ width: 40, height: 40, borderRadius: 10, border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', background: 'rgba(255,255,255,0.12)', backdropFilter: 'blur(8px)' }}>
              <IconX size={18} color="white" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function AIPredictionBlock({ order, predicting, startPredict, correcting, setCorrecting, correctValue, setCorrectValue, submitCorrection }) {
  const ai = order.ai;
  const hasPrediction = ai && !order.manually_priced;

  return (
    <div style={{
      background: 'linear-gradient(140deg, var(--cream-2) 0%, var(--cream) 80%)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--radius-lg)',
      padding: 26,
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--ink)', display: 'grid', placeItems: 'center' }}>
              <IconSparkle size={14} color="var(--cream)" />
            </div>
            <span style={{ fontWeight: 600, fontSize: 13, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Vlerësim AI</span>
          </div>
          <h2 className="display" style={{ margin: '6px 0 0', fontSize: 22, fontWeight: 600 }}>
            Çmimi i tortës së personalizuar
          </h2>
        </div>
        {hasPrediction && !predicting && (
          <button className="icon-btn bordered" onClick={startPredict} title="Ri-parashiko">
            <IconRefresh size={16} />
          </button>
        )}
      </div>

      {predicting ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, padding: '20px 0' }}>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
            <span className="spinner lg" style={{ borderColor: 'rgba(59,31,10,0.15)', borderTopColor: 'var(--rose)' }} />
            <div>
              <div style={{ fontWeight: 600 }}>Duke analizuar foton…</div>
              <div className="muted" style={{ fontSize: 13 }}>Duke analizuar tortën dhe krahasuar me setin e stërvitjes.</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="muted" style={{ fontSize: 12 }}>
              <span className="serif-italic">EfficientNetB0 · 224×224 · regression head</span>
            </div>
            <div className="confidence-track">
              <div className="confidence-fill" style={{ width: '80%', background: 'var(--rose)', animation: 'pulse 1.4s ease-in-out infinite' }} />
            </div>
          </div>
        </div>
      ) : !ai ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'flex-start' }}>
          <p style={{ margin: 0, color: 'var(--ink-2)' }}>Asnjë parashikim akoma. Ekzekutoni inferimin për të marrë një çmim të sugjeruar për këtë tortë.</p>
          <button className="btn rose" onClick={startPredict}>
            <IconBrain size={16} color="white" /> Parashiko çmimin
          </button>
        </div>
      ) : order.manually_priced ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, alignItems: 'center' }}>
          <div>
            <div className="muted" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 6 }}>Parashikuar nga AI</div>
            <div className="display tabular" style={{ fontSize: 30, fontWeight: 500, color: 'var(--ink-mute)', textDecoration: 'line-through' }}>
              {window.formatEURP(ai.predicted_price)}
            </div>
          </div>
          <div>
            <div className="muted" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 6 }}>Çmimi final (vendosur nga ju)</div>
            <div className="display tabular" style={{ fontSize: 38, fontWeight: 600, color: 'var(--rose)', lineHeight: 1 }}>
              {window.formatEURP(order.payment?.total_price)}
            </div>
            <div style={{ marginTop: 6, fontSize: 12, color: 'var(--ink-mute)' }}>
              Korrigjimi u radhit — modeli do të ristërvitet sonte në 02:00.
            </div>
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
            <span className="display tabular" style={{ fontSize: 60, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1 }}>
              {window.formatEURP(ai.predicted_price)}
            </span>
            <span className="muted" style={{ fontSize: 13.5 }}>i vlerësuar</span>
          </div>

          <ConfidenceBar score={ai.conf_score} />

          <div style={{ fontSize: 13, color: 'var(--ink-2)', display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            <span>
              Bazuar në <strong className="tabular">{ai.similar_count}</strong> torta të ngjashme të çmuara më parë
            </span>
          </div>

          {ai.confidence === 'low' && (
            <div style={{ padding: '12px 16px', background: 'var(--red-soft)', borderRadius: 10, color: '#7a2424', display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13.5, lineHeight: 1.5 }}>
              <IconAlertCircle size={16} color="#7a2424" style={{ marginTop: 2, flexShrink: 0 }} />
              Kjo tortë duket shumë ndryshe nga ato që kemi çmuar më parë — trajtojeni këtë vlerësim me kujdes dhe besojini instinktit tuaj.
            </div>
          )}

          {correcting ? (
            <div style={{ background: 'white', padding: 16, borderRadius: 12, border: '1px solid var(--line)' }}>
              <div style={{ fontSize: 13.5, marginBottom: 10 }}>Çfarë duhet të jetë çmimi në të vërtetë?</div>
              <div style={{ display: 'flex', gap: 10 }}>
                <input className="input" type="number" autoFocus step="0.01" placeholder="p.sh. 95.00"
                       value={correctValue} onChange={(e) => setCorrectValue(e.target.value)} />
                <button className="btn" onClick={submitCorrection} disabled={!correctValue}>Dërgo korrigjimin</button>
                <button className="btn secondary" onClick={() => setCorrecting(false)}>Anulo</button>
              </div>
              <div className="muted" style={{ fontSize: 12, marginTop: 8 }}>Korrigjimi juaj stërvit modelin gjatë natës.</div>
            </div>
          ) : (
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <button className="btn green" onClick={() => {
                window.__app_accept_ai(order.id);
              }}>
                <IconCheck size={16} color="white" /> Duket mirë · përdor këtë çmim
              </button>
              <button className="btn secondary" onClick={() => { setCorrecting(true); setCorrectValue(ai.predicted_price.toFixed(2)); }}>
                Jo korrekte — vendos manualisht
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ── NEW ORDER FORM ────────────────────────────────────────────────────────

function NewOrder({ onCreate, onCancel, addToast, flavours, pricingConfig, baklavaPricing = { tepsi: 40, kg: 10 }, orders = [] }) {
  const { diameters: availDiameters, personSizes: availPersonSizes, basePrices } = pricingConfig || {
    diameters: [10, 12, 14], personSizes: window.PERSON_SIZES, basePrices: window.BASE_PRICES,
  };

  // Deduplicated customer list from past orders, most recent first
  const knownCustomers = React.useMemo(() => {
    const seen = new Map();
    [...orders].reverse().forEach(o => {
      const key = o.customer_name?.trim().toLowerCase();
      if (key && !seen.has(key)) {
        seen.set(key, { name: o.customer_name, contact: o.customer_contact });
      }
    });
    return Array.from(seen.values());
  }, [orders]);

  const [type, setType] = React.useState('standard');
  const [baklavaSoldAs, setBaklavaSoldAs] = React.useState('tepsi');
  const [baklavaqty, setBaklavaqty] = React.useState(1);
  const [baklavaTepsiOwner, setBaklavaTepsiOwner] = React.useState('ours');
  const [name, setName] = React.useState('');
  const [contact, setContact] = React.useState({});
  const [nameFocused, setNameFocused] = React.useState(false);
  const [flavour, setFlavour] = React.useState(flavours[0]);
  const [persons, setPersons] = React.useState(10);
  const [tiers, setTiers] = React.useState([{ diameter: null, variant: null }]);
  const [cakeText, setCakeText] = React.useState('');
  const [dueDate, setDueDate] = React.useState(new Date().toISOString().slice(0, 10));
  const [notes, setNotes] = React.useState('');
  const [imageUrl, setImageUrl] = React.useState(null);
  const [imagePreview, setImagePreview] = React.useState(null);
  const [uploading, setUploading] = React.useState(false);

  const sizeValid = tiers[0]?.diameter != null;
  const baklavaValid = baklavaSoldAs && baklavaqty > 0;
  const canSubmit = name.trim() && dueDate && !uploading && (type === 'baklava' ? baklavaValid : sizeValid);

  const nameSuggestions = React.useMemo(() => {
    const q = name.trim().toLowerCase();
    if (!q) return [];
    return knownCustomers.filter(c => c.name.toLowerCase().includes(q)).slice(0, 6);
  }, [name, knownCustomers]);

  const handleImageFile = (file) => {
    if (!file) return;
    setImagePreview(URL.createObjectURL(file));
    setUploading(true);
    window.api.uploadImage(file)
      .then(({ url }) => setImageUrl(url))
      .catch(() => addToast('Ngarkimi i fotos dështoi'))
      .finally(() => setUploading(false));
  };

  const updateTier = (i, key, val) => setTiers(tiers.map((t, j) => j === i ? { ...t, [key]: val } : t));
  const addTier = () => setTiers([...tiers, { diameter: null, variant: null }]);
  const removeTier = (i) => setTiers(tiers.filter((_, j) => j !== i));

  const submit = () => {
    if (type === 'baklava') {
      const totalPrice = baklavaSoldAs === 'tepsi'
        ? baklavaqty * baklavaPricing.tepsi
        : baklavaqty * baklavaPricing.kg;
      onCreate({
        customer_name: name.trim(),
        customer_contact: contact,
        type: 'baklava',
        flavour: null, persons: null, diameter: null, variant: null,
        cake_text: '', art: null,
        image_url: imageUrl ?? null,
        due_date: dueDate, status: 'pending', notes: notes.trim(),
        baklava_data: {
          sold_as: baklavaSoldAs,
          quantity: baklavaqty,
          ...(baklavaSoldAs === 'tepsi' ? { tepsi_owner: baklavaTepsiOwner, tepsi_returned: false } : {}),
        },
        payment: { total_price: totalPrice, deposit_amount: null, deposit_paid_at: null, fully_paid_at: null },
      });
      addToast('Porosia u krijua');
      return;
    }

    const t0 = tiers[0] || {};
    const extraTiers = tiers.slice(1).filter(t => t.diameter).map(t => ({ size: t.diameter, qty: 1, variant: t.variant || null }));
    const newOrder = {
      customer_name: name.trim(),
      customer_contact: contact,
      type,
      flavour: type === 'standard' ? flavour : null,
      persons: type === 'standard' ? persons : null,
      diameter: t0.diameter,
      variant: t0.diameter ? t0.variant : null,
      flats: extraTiers.length > 0 ? extraTiers : null,
      cake_text: type === 'standard' ? cakeText : '',
      art: type === 'standard' ? sampleArtFor(flavour) : null,
      image_url: imageUrl ?? null,
      due_date: dueDate, status: 'pending', notes: notes.trim(),
      payment: {
        total_price: type === 'standard' ? (basePrices[persons] ?? null) : null,
        deposit_amount: null, deposit_paid_at: null, fully_paid_at: null,
      },
    };
    if (type === 'custom') newOrder.ai = null;
    onCreate(newOrder);
    addToast('Porosia u krijua');
  };

  return (
    <div className="fade-in" style={{ maxWidth: 720, display: 'flex', flexDirection: 'column', gap: 22 }}>
      <button onClick={onCancel} className="chip" style={{ alignSelf: 'flex-start' }}>
        <IconArrowLeft size={14} /> Anulo
      </button>

      <div>
        <h1 className="display" style={{ margin: 0, fontSize: 36, fontWeight: 600, letterSpacing: '-0.01em' }}>Porosi e re</h1>
        <p className="muted" style={{ margin: '4px 0 0' }}>
          {window.FEATURES.aiPricing
            ? 'Shkruani detajet. AI menaxhon çmimin për dizajnet e personalizuara.'
            : 'Shkruani detajet e porosisë.'}
        </p>
      </div>

      {/* Type chooser */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 180px), 1fr))', gap: 12 }}>
        <button onClick={() => setType('standard')} className="order-card" style={{
          padding: 18, cursor: 'pointer',
          borderColor: type === 'standard' ? 'var(--ink)' : 'var(--line)',
          background: type === 'standard' ? 'var(--cream-2)' : 'white',
          flexDirection: 'column', alignItems: 'flex-start', textAlign: 'left',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <IconCake size={20} />
            <strong style={{ fontSize: 15 }}>Standard</strong>
          </div>
          <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>Shije, madhësi, mesazh. Çmimi nga tabela.</span>
        </button>
        <button onClick={() => setType('custom')} className="order-card" style={{
          padding: 18, cursor: 'pointer',
          borderColor: type === 'custom' ? 'var(--rose)' : 'var(--line)',
          background: type === 'custom' ? 'rgba(212, 96, 122, 0.06)' : 'white',
          flexDirection: 'column', alignItems: 'flex-start', textAlign: 'left',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <IconSparkle size={20} color="var(--rose)" />
            <strong style={{ fontSize: 15 }}>I personalizuar</strong>
          </div>
          <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>Foto nga klienti. Çmimi vendoset manualisht.</span>
        </button>
        <button onClick={() => setType('baklava')} className="order-card" style={{
          padding: 18, cursor: 'pointer',
          borderColor: type === 'baklava' ? 'var(--amber)' : 'var(--line)',
          background: type === 'baklava' ? 'rgba(216, 147, 49, 0.08)' : 'white',
          flexDirection: 'column', alignItems: 'flex-start', textAlign: 'left',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <IconCake size={20} color="var(--amber)" />
            <strong style={{ fontSize: 15 }}>Bakllava</strong>
          </div>
          <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>Me tepsi ose me kg. Çmimi llogaritet automatikisht.</span>
        </button>
      </div>

      {/* Form */}
      <div className="card" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
          <div className="field" style={{ position: 'relative' }}>
            <label className="field-label">Emri i klientit</label>
            <input
              className="input"
              placeholder="p.sh. Drita Shala"
              value={name}
              autoComplete="off"
              onFocus={() => setNameFocused(true)}
              onBlur={() => setTimeout(() => setNameFocused(false), 150)}
              onChange={e => setName(e.target.value)}
            />
            {nameFocused && nameSuggestions.length > 0 && (
              <div style={{
                position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 20,
                background: 'white', border: '1px solid var(--line-2)', borderRadius: 12,
                boxShadow: '0 8px 24px -8px rgba(59,31,10,0.18)', overflow: 'hidden', marginTop: 4,
              }}>
                {nameSuggestions.map(c => (
                  <button key={c.name} type="button"
                    onMouseDown={() => { setName(c.name); setContact(c.contact || {}); setNameFocused(false); }}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      width: '100%', padding: '10px 14px', border: 'none',
                      background: 'transparent', cursor: 'pointer', textAlign: 'left',
                      borderBottom: '1px solid var(--line)',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--cream-2)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >
                    <Avatar name={c.name} size="sm" />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>{c.name}</div>
                      {c.contact && Object.keys(c.contact).length > 0 && (
                        <ContactDisplay contact={c.contact} compact />
                      )}
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
          <div className="field">
            <label className="field-label">Data e dorëzimit</label>
            <input className="input" type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} />
          </div>
        </div>

        <div className="field">
          <label className="field-label" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>Si të kontaktojmë</span>
            <span style={{ fontSize: 10, fontWeight: 500, textTransform: 'none', letterSpacing: 0, padding: '1px 7px', background: 'var(--cream-2)', borderRadius: 999, color: 'var(--ink-mute)' }}>opsionale</span>
          </label>
          <ContactPicker value={contact} onChange={setContact} />
          <span className="muted" style={{ fontSize: 11.5 }}>Zgjidhni çdo kanal që klienti përdor.</span>
        </div>

        {/* Baklava-specific fields */}
        {type === 'baklava' && (
          <div className="slide-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div className="field">
              <label className="field-label">Shitet si</label>
              <div style={{ display: 'flex', gap: 8 }}>
                <button className={`chip ${baklavaSoldAs === 'tepsi' ? 'active' : ''}`}
                  style={{ height: 44, padding: '0 20px', fontSize: 14, fontWeight: 600,
                    background: baklavaSoldAs === 'tepsi' ? 'var(--amber)' : 'white',
                    borderColor: baklavaSoldAs === 'tepsi' ? 'var(--amber)' : 'var(--line)',
                    color: baklavaSoldAs === 'tepsi' ? 'white' : 'var(--ink-2)' }}
                  onClick={() => { setBaklavaSoldAs('tepsi'); setBaklavaqty(1); }}>
                  Tepsi
                </button>
                <button className={`chip ${baklavaSoldAs === 'kg' ? 'active' : ''}`}
                  style={{ height: 44, padding: '0 20px', fontSize: 14, fontWeight: 600,
                    background: baklavaSoldAs === 'kg' ? 'var(--amber)' : 'white',
                    borderColor: baklavaSoldAs === 'kg' ? 'var(--amber)' : 'var(--line)',
                    color: baklavaSoldAs === 'kg' ? 'white' : 'var(--ink-2)' }}
                  onClick={() => { setBaklavaSoldAs('kg'); setBaklavaqty(1); }}>
                  Kg
                </button>
              </div>
            </div>

            <div className="field">
              <label className="field-label">Sasia</label>
              {baklavaSoldAs === 'tepsi' ? (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {[1, 2, 3, 4, 5].map(q => (
                    <button key={q} onClick={() => setBaklavaqty(q)} className="chip"
                      style={{ height: 44, padding: '0 18px', fontSize: 14, fontWeight: 600,
                        background: baklavaqty === q ? 'var(--amber)' : 'white',
                        borderColor: baklavaqty === q ? 'var(--amber)' : 'var(--line)',
                        color: baklavaqty === q ? 'white' : 'var(--ink-2)' }}>
                      {q}
                    </button>
                  ))}
                </div>
              ) : (
                <div style={{ position: 'relative', maxWidth: 160 }}>
                  <input className="input" type="number" min="0.1" step="0.1" placeholder="p.sh. 1.5"
                    value={baklavaqty || ''} onChange={e => setBaklavaqty(parseFloat(e.target.value) || 0)}
                    style={{ paddingRight: 36 }} />
                  <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 13, color: 'var(--ink-mute)', pointerEvents: 'none' }}>kg</span>
                </div>
              )}
            </div>

            {baklavaSoldAs === 'tepsi' && (
              <div className="field">
                <label className="field-label">Tepsi</label>
                <div style={{ display: 'flex', gap: 8 }}>
                  {[{ val: 'ours', label: 'Tepsi jonë', sub: 'duhet kthyer' }, { val: 'customer', label: 'Tepsi i klientit', sub: 'nuk kthehet' }].map(opt => (
                    <button key={opt.val} onClick={() => setBaklavaTepsiOwner(opt.val)}
                      style={{ flex: 1, padding: '10px 12px', borderRadius: 10, border: '1.5px solid',
                        borderColor: baklavaTepsiOwner === opt.val ? 'var(--amber)' : 'var(--line)',
                        background: baklavaTepsiOwner === opt.val ? 'rgba(216,147,49,0.08)' : 'white',
                        cursor: 'pointer', textAlign: 'left' }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: baklavaTepsiOwner === opt.val ? 'var(--amber)' : 'var(--ink)' }}>{opt.label}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', marginTop: 2 }}>{opt.sub}</div>
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div style={{ padding: '12px 16px', background: 'rgba(216, 147, 49, 0.08)', borderRadius: 10, border: '1px solid rgba(216, 147, 49, 0.2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>
                {baklavaqty} {baklavaSoldAs === 'tepsi' ? `tepsi × €${baklavaPricing.tepsi}` : `kg × €${baklavaPricing.kg}`}
              </span>
              <span className="display tabular" style={{ fontSize: 22, fontWeight: 600, color: 'var(--amber)' }}>
                €{baklavaSoldAs === 'tepsi'
                  ? (baklavaqty * baklavaPricing.tepsi).toFixed(2)
                  : (baklavaqty * baklavaPricing.kg).toFixed(2)}
              </span>
            </div>
          </div>
        )}

        {/* Tiers — hidden for baklava */}
        {type !== 'baklava' && <div className="field">
          <label className="field-label">Kate</label>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {tiers.map((tier, i) => (
              <div key={i} style={{ padding: '14px 16px', background: 'var(--cream-2)', borderRadius: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: i === 0 ? 'var(--ink)' : 'var(--ink-mute)' }}>
                    Kati {i + 1}{i === 0 ? ' · bazë' : ''}
                  </span>
                  {i > 0 && (
                    <button onClick={() => removeTier(i)} className="icon-btn" style={{ width: 26, height: 26 }}>
                      <IconX size={13} />
                    </button>
                  )}
                </div>

                {/* Diameter */}
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {availDiameters.map(d => (
                    <button key={d} onClick={() => updateTier(i, 'diameter', tier.diameter === d ? null : d)} className="chip"
                      style={{
                        background: tier.diameter === d ? 'var(--ink)' : 'white',
                        color: tier.diameter === d ? 'var(--cream)' : 'var(--ink-2)',
                        borderColor: tier.diameter === d ? 'var(--ink)' : 'var(--line)',
                        height: 44, padding: '0 18px', fontSize: 14, fontWeight: 600,
                      }}>
                      <span className="tabular">{d}</span><span style={{ opacity: 0.7, fontWeight: 400, marginLeft: 2 }}>cm</span>
                    </button>
                  ))}
                </div>

                {/* Shtresa shtesë — only when diameter is picked */}
                {tier.diameter && (
                  <div className="slide-up">
                    <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)', marginBottom: 6 }}>Shtresa shtesë</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                      <button onClick={() => updateTier(i, 'variant', null)} className="chip"
                        style={{
                          background: tier.variant == null ? 'var(--ink)' : 'white',
                          color: tier.variant == null ? 'var(--cream)' : 'var(--ink-mute)',
                          borderColor: tier.variant == null ? 'var(--ink)' : 'var(--line)',
                          height: 36, padding: '0 14px', fontSize: 13,
                        }}>
                        Asnjë
                      </button>
                      {[1, 2, 3, 4].map(n => (
                        <button key={n} onClick={() => updateTier(i, 'variant', n)} className="chip"
                          style={{
                            background: tier.variant === n ? 'var(--rose)' : 'white',
                            color: tier.variant === n ? 'white' : 'var(--ink-2)',
                            borderColor: tier.variant === n ? 'var(--rose)' : 'var(--line)',
                            height: 36, padding: '0 14px', fontSize: 14, fontWeight: 600,
                          }}>
                          +{n}
                        </button>
                      ))}
                    </div>
                    <span className="muted" style={{ fontSize: 11.5, marginTop: 6, display: 'block' }}>
                      {tier.variant
                        ? `${tier.diameter}cm · ${tier.variant} shtresë${tier.variant === 1 ? '' : 'a'} shtesë`
                        : `${tier.diameter}cm, pa shtresa shtesë`}
                    </span>
                  </div>
                )}
              </div>
            ))}

            <button onClick={addTier} className="chip"
              style={{ alignSelf: 'flex-start', height: 36, padding: '0 14px', fontSize: 13, color: 'var(--ink-2)' }}>
              <IconPlus size={13} color="var(--ink-2)" /> Shto kat
            </button>
          </div>
        </div>}

        {type === 'standard' ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
            <div className="field">
              <label className="field-label">Shija</label>
              <select className="select" value={flavour} onChange={e => setFlavour(e.target.value)}>
                {flavours.map(f => <option key={f} value={f}>{f}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="field-label">Persona</label>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {availPersonSizes.map(n => (
                  <button key={n} onClick={() => setPersons(n)} className="chip"
                          style={{ background: persons === n ? 'var(--ink)' : 'transparent', color: persons === n ? 'var(--cream)' : 'var(--ink-2)', borderColor: persons === n ? 'var(--ink)' : 'var(--line)', height: 36, padding: '0 14px' }}>
                    {n}{n === availPersonSizes[availPersonSizes.length - 1] && n >= 50 ? '+' : ''}
                  </button>
                ))}
              </div>
              <div className="muted" style={{ fontSize: 11.5 }}>Çmimi referent: {window.formatEUR(basePrices[persons])}</div>
            </div>
            <div className="field" style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">Teksti mbi tortë</label>
              <input className="input" placeholder="p.sh. Gëzuar ditëlindjen Mami" value={cakeText} onChange={e => setCakeText(e.target.value)} />
            </div>
          </div>
        ) : null}

        {/* Photo upload — available for all order types */}
        <div className="field">
          <label className="field-label" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>Foto e tortës</span>
            <span style={{ fontSize: 10, fontWeight: 500, textTransform: 'none', letterSpacing: 0, padding: '1px 7px', background: 'var(--cream-2)', borderRadius: 999, color: 'var(--ink-mute)' }}>opsionale</span>
          </label>
          {imagePreview ? (
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <div style={{ width: 96, height: 96, borderRadius: 12, overflow: 'hidden', flexShrink: 0, background: 'var(--cream-2)', position: 'relative' }}>
                <img src={imagePreview} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                {uploading && (
                  <div style={{ position: 'absolute', inset: 0, background: 'rgba(253,248,243,0.7)', display: 'grid', placeItems: 'center' }}>
                    <span className="spinner" style={{ borderColor: 'rgba(59,31,10,0.2)', borderTopColor: 'var(--ink)' }} />
                  </div>
                )}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600 }}>{uploading ? 'Duke ngarkuar…' : 'Foto gati'}</div>
                <div className="muted" style={{ fontSize: 13 }}>
                  {uploading ? 'Ju lutemi prisni.' : "Do t'i bashkëngjitet kësaj porosie."}
                </div>
              </div>
              <button className="btn secondary sm" onClick={() => { setImagePreview(null); setImageUrl(null); }}>Hiq</button>
            </div>
          ) : (
            <label style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
              padding: '28px 20px', border: '1.5px dashed var(--line-2)', borderRadius: 12,
              cursor: 'pointer', background: 'var(--cream-2)',
            }}>
              <input type="file" accept="image/*" style={{ display: 'none' }}
                onChange={e => handleImageFile(e.target.files[0])} />
              <IconPlus size={20} color="var(--ink-mute)" />
              <span style={{ fontSize: 13, color: 'var(--ink-mute)' }}>Shtypni për të ngarkuar foto</span>
            </label>
          )}
        </div>

        <div className="field">
          <label className="field-label">Shënime</label>
          <textarea className="textarea" placeholder="Alergji, orari i marrjes, kërkesa speciale…" value={notes} onChange={e => setNotes(e.target.value)} />
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
        <button className="btn secondary" onClick={onCancel}>Anulo</button>
        <button className="btn" disabled={!canSubmit} onClick={submit}>
          <IconCheck size={16} color="var(--cream)" /> Krijo porosinë
        </button>
      </div>
    </div>
  );
}

function EditOrderForm({ order, flavours, pricingConfig, baklavaPricing = { tepsi: 40, kg: 10 }, onSave, onCancel, addToast }) {
  const { diameters: availDiameters = [10, 12, 14], personSizes: availPersonSizes = window.PERSON_SIZES, basePrices = window.BASE_PRICES } = pricingConfig || {};

  // Initialise state from the existing order
  const [name, setName] = React.useState(order.customer_name || '');
  const [contact, setContact] = React.useState(order.customer_contact || {});
  const [dueDate, setDueDate] = React.useState(order.due_date || '');
  const [notes, setNotes] = React.useState(order.notes || '');

  // Standard / custom cake fields
  const [flavour, setFlavour] = React.useState(order.flavour || flavours[0] || '');
  const [persons, setPersons] = React.useState(order.persons || availPersonSizes[0] || 10);
  const [diameter, setDiameter] = React.useState(order.diameter || null);
  const [variant, setVariant] = React.useState(order.variant || null);
  const [cakeText, setCakeText] = React.useState(order.cake_text || '');

  // Baklava fields
  const initBak = order.baklava_data || {};
  const [baklavaSoldAs, setBaklavaSoldAs] = React.useState(initBak.sold_as || 'tepsi');
  const [baklavaqty, setBaklavaqty] = React.useState(initBak.quantity || 1);
  const [baklavaTepsiOwner, setBaklavaTepsiOwner] = React.useState(initBak.tepsi_owner || 'ours');

  const type = order.type;

  const canSave = name.trim() && dueDate && (type === 'baklava' ? baklavaqty > 0 : diameter != null);

  const submit = () => {
    const patch = {
      customer_name: name.trim(),
      customer_contact: contact,
      due_date: dueDate,
      notes: notes.trim(),
    };
    if (type === 'baklava') {
      patch.baklava_data = {
        ...initBak,
        sold_as: baklavaSoldAs,
        quantity: baklavaqty,
        ...(baklavaSoldAs === 'tepsi' ? { tepsi_owner: baklavaTepsiOwner } : {}),
      };
      const totalPrice = baklavaSoldAs === 'tepsi'
        ? baklavaqty * baklavaPricing.tepsi
        : baklavaqty * baklavaPricing.kg;
      patch.payment = { total_price: totalPrice };
    } else {
      patch.diameter = diameter;
      patch.variant = variant;
      if (type === 'standard') {
        patch.flavour = flavour;
        patch.persons = persons;
        patch.cake_text = cakeText;
      }
    }
    onSave(patch);
  };

  return (
    <div className="fade-in" style={{ maxWidth: 720, display: 'flex', flexDirection: 'column', gap: 22 }}>
      <button onClick={onCancel} className="chip" style={{ alignSelf: 'flex-start' }}>
        <IconArrowLeft size={14} /> Anulo
      </button>

      <div>
        <div className="muted" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 4 }}>
          Porosia #{order.id.slice(-4)} · {type === 'standard' ? 'Standard' : type === 'baklava' ? 'Bakllava' : 'I personalizuar'}
        </div>
        <h1 className="display" style={{ margin: 0, fontSize: 32, fontWeight: 600, letterSpacing: '-0.01em' }}>Ndrysho porosinë</h1>
      </div>

      <div className="card" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

        {/* Customer name + date */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
          <div className="field">
            <label className="field-label">Emri i klientit</label>
            <input className="input" value={name} onChange={e => setName(e.target.value)} />
          </div>
          <div className="field">
            <label className="field-label">Data e dorëzimit</label>
            <input className="input" type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} />
          </div>
        </div>

        {/* Contact */}
        <div className="field">
          <label className="field-label">Si të kontaktojmë</label>
          <ContactPicker value={contact} onChange={setContact} />
        </div>

        {/* Baklava-specific */}
        {type === 'baklava' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div className="field">
              <label className="field-label">Shitet si</label>
              <div style={{ display: 'flex', gap: 8 }}>
                {[{ val: 'tepsi', label: 'Tepsi' }, { val: 'kg', label: 'Kg' }].map(opt => (
                  <button key={opt.val} className="chip"
                    style={{ height: 44, padding: '0 20px', fontSize: 14, fontWeight: 600,
                      background: baklavaSoldAs === opt.val ? 'var(--amber)' : 'white',
                      borderColor: baklavaSoldAs === opt.val ? 'var(--amber)' : 'var(--line)',
                      color: baklavaSoldAs === opt.val ? 'white' : 'var(--ink-2)' }}
                    onClick={() => { setBaklavaSoldAs(opt.val); setBaklavaqty(1); }}>
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            <div className="field">
              <label className="field-label">Sasia</label>
              {baklavaSoldAs === 'tepsi' ? (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {[1, 2, 3, 4, 5].map(q => (
                    <button key={q} onClick={() => setBaklavaqty(q)} className="chip"
                      style={{ height: 44, padding: '0 18px', fontSize: 14, fontWeight: 600,
                        background: baklavaqty === q ? 'var(--amber)' : 'white',
                        borderColor: baklavaqty === q ? 'var(--amber)' : 'var(--line)',
                        color: baklavaqty === q ? 'white' : 'var(--ink-2)' }}>
                      {q}
                    </button>
                  ))}
                </div>
              ) : (
                <div style={{ position: 'relative', maxWidth: 160 }}>
                  <input className="input" type="number" min="0.1" step="0.1"
                    value={baklavaqty || ''} onChange={e => setBaklavaqty(parseFloat(e.target.value) || 0)}
                    style={{ paddingRight: 36 }} />
                  <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 13, color: 'var(--ink-mute)', pointerEvents: 'none' }}>kg</span>
                </div>
              )}
            </div>

            {baklavaSoldAs === 'tepsi' && (
              <div className="field">
                <label className="field-label">Tepsi</label>
                <div style={{ display: 'flex', gap: 8 }}>
                  {[{ val: 'ours', label: 'Tepsi jonë', sub: 'duhet kthyer' }, { val: 'customer', label: 'Tepsi i klientit', sub: 'nuk kthehet' }].map(opt => (
                    <button key={opt.val} onClick={() => setBaklavaTepsiOwner(opt.val)}
                      style={{ flex: 1, padding: '10px 12px', borderRadius: 10, border: '1.5px solid',
                        borderColor: baklavaTepsiOwner === opt.val ? 'var(--amber)' : 'var(--line)',
                        background: baklavaTepsiOwner === opt.val ? 'rgba(216,147,49,0.08)' : 'white',
                        cursor: 'pointer', textAlign: 'left' }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: baklavaTepsiOwner === opt.val ? 'var(--amber)' : 'var(--ink)' }}>{opt.label}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', marginTop: 2 }}>{opt.sub}</div>
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div style={{ padding: '12px 16px', background: 'rgba(216,147,49,0.08)', borderRadius: 10, border: '1px solid rgba(216,147,49,0.2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>
                {baklavaqty} {baklavaSoldAs === 'tepsi' ? `tepsi × €${baklavaPricing.tepsi}` : `kg × €${baklavaPricing.kg}`}
              </span>
              <span className="display tabular" style={{ fontSize: 22, fontWeight: 600, color: 'var(--amber)' }}>
                €{(baklavaSoldAs === 'tepsi' ? baklavaqty * baklavaPricing.tepsi : baklavaqty * baklavaPricing.kg).toFixed(2)}
              </span>
            </div>
          </div>
        )}

        {/* Cake size (standard + custom) */}
        {type !== 'baklava' && (
          <div className="field">
            <label className="field-label">Diametri</label>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 10 }}>
              {availDiameters.map(d => (
                <button key={d} onClick={() => { setDiameter(diameter === d ? null : d); if (diameter === d) setVariant(null); }} className="chip"
                  style={{ background: diameter === d ? 'var(--ink)' : 'white', color: diameter === d ? 'var(--cream)' : 'var(--ink-2)',
                    borderColor: diameter === d ? 'var(--ink)' : 'var(--line)', height: 44, padding: '0 18px', fontSize: 14, fontWeight: 600 }}>
                  <span className="tabular">{d}</span><span style={{ opacity: 0.7, fontWeight: 400, marginLeft: 2 }}>cm</span>
                </button>
              ))}
            </div>
            {diameter && (
              <div className="slide-up">
                <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)', marginBottom: 6 }}>Shtresa shtesë</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  <button onClick={() => setVariant(null)} className="chip"
                    style={{ background: variant == null ? 'var(--ink)' : 'white', color: variant == null ? 'var(--cream)' : 'var(--ink-mute)',
                      borderColor: variant == null ? 'var(--ink)' : 'var(--line)', height: 36, padding: '0 14px', fontSize: 13 }}>
                    Asnjë
                  </button>
                  {[1, 2, 3, 4].map(n => (
                    <button key={n} onClick={() => setVariant(n)} className="chip"
                      style={{ background: variant === n ? 'var(--rose)' : 'white', color: variant === n ? 'white' : 'var(--ink-2)',
                        borderColor: variant === n ? 'var(--rose)' : 'var(--line)', height: 36, padding: '0 14px', fontSize: 14, fontWeight: 600 }}>
                      +{n}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Standard-only fields */}
        {type === 'standard' && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14 }}>
            <div className="field">
              <label className="field-label">Shija</label>
              <select className="select" value={flavour} onChange={e => setFlavour(e.target.value)}>
                {flavours.map(f => <option key={f} value={f}>{f}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="field-label">Persona</label>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {availPersonSizes.map(n => (
                  <button key={n} onClick={() => setPersons(n)} className="chip"
                    style={{ background: persons === n ? 'var(--ink)' : 'transparent', color: persons === n ? 'var(--cream)' : 'var(--ink-2)',
                      borderColor: persons === n ? 'var(--ink)' : 'var(--line)', height: 36, padding: '0 14px' }}>
                    {n}
                  </button>
                ))}
              </div>
            </div>
            <div className="field" style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">Teksti mbi tortë</label>
              <input className="input" value={cakeText} onChange={e => setCakeText(e.target.value)} />
            </div>
          </div>
        )}

        {/* Notes */}
        <div className="field">
          <label className="field-label">Shënime</label>
          <textarea className="textarea" value={notes} onChange={e => setNotes(e.target.value)} />
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
        <button className="btn secondary" onClick={onCancel}>Anulo</button>
        <button className="btn" disabled={!canSave} onClick={submit}>
          <IconCheck size={16} color="var(--cream)" /> Ruaj ndryshimet
        </button>
      </div>
    </div>
  );
}

function sampleArtFor(flavour) {
  const map = {
    Chocolate: 'choc-drip',
    Pistachio: 'pistachio',
    Vanilla: 'wedding-white',
    'Red Velvet': 'rose-tier',
    Strawberry: 'birthday',
    Lemon: 'lemon',
    Tiramisu: 'wedding-white',
    Hazelnut: 'choc-drip',
    Carrot: 'birthday',
    Coconut: 'wedding-white',
    'Black Forest': 'black-forest',
  };
  return map[flavour] || 'rose-tier';
}

Object.assign(window, { OrdersList, OrderDetail, NewOrder, AIPredictionBlock });
