/* ========== Orders ========== */
function OrdersView({ initialOrderId, initialStage, onNav }) {
  const state = useStore();
  const [filterStage, setFilterStage] = useState(initialStage || 'all');
  const [filterType, setFilterType] = useState('all');
  const [q, setQ] = useState('');
  const [selectedId, setSelectedId] = useState(initialOrderId || null);
  const [showNew, setShowNew] = useState(false);

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

  const filtered = state.orders.filter(o => {
    if (filterStage !== 'all' && o.stage !== filterStage) return false;
    if (filterType !== 'all' && o.type !== filterType) return false;
    if (q) {
      const text = (o.orderNo + ' ' + o.title + ' ' + customerName(o.customerId)).toLowerCase();
      if (!text.includes(q.toLowerCase())) return false;
    }
    return true;
  });

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

  return (
    <div>
      <div className="toolbar">
        <div className="search" style={{ flex: 1, maxWidth: 380 }}>
          <Icon name="search" size={14}/>
          <input
            type="text"
            placeholder="Search orders, clients, services…"
            value={q}
            onChange={e=>setQ(e.target.value)}
            style={{ width: '100%' }}
          />
        </div>
        <div className="filters">
          <select value={filterStage} onChange={e=>setFilterStage(e.target.value)}>
            <option value="all">All stages</option>
            {state.stages.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
          </select>
          <select value={filterType} onChange={e=>setFilterType(e.target.value)}>
            <option value="all">All services</option>
            <option value="visa">Visa</option>
            <option value="translation">Translation</option>
            <option value="consulting">Consulting</option>
          </select>
        </div>
        <div className="spacer"/>
        <button className="btn primary" onClick={() => setShowNew(true)}>
          <Icon name="plus" size={14}/> New order
        </button>
      </div>

      <div className="card">
        {filtered.length === 0 ? (
          <div className="empty">
            <h4>No orders match these filters</h4>
            <p>Try clearing filters, or create a new order.</p>
            <button className="btn primary" onClick={() => setShowNew(true)}>
              <Icon name="plus" size={14}/> New order
            </button>
          </div>
        ) : (
          <table className="tbl">
            <thead>
              <tr>
                <th>Order</th>
                <th>Client</th>
                <th>Service</th>
                <th>Stage</th>
                <th>Created</th>
                <th>Due</th>
                <th>Progress</th>
                <th className="num">Amount</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(o => {
                const total = (o.checklist||[]).length;
                const done = (o.checklist||[]).filter(c=>c.done).length;
                const pct = total ? Math.round(done/total*100) : 0;
                const overdue = o.dueAt && o.dueAt < Date.now() && !['delivered','approved','rejected'].includes(o.stage);
                return (
                  <tr key={o.id} className="clickable" onClick={() => setSelectedId(o.id)}>
                    <td><span className="order-num">{o.orderNo}</span></td>
                    <td>{customerName(o.customerId)}</td>
                    <td>
                      <span style={{ fontSize: 16, marginRight: 6 }}>{o.type === 'visa' ? countryFlag(o.country) : '📝'}</span>
                      {o.title}
                    </td>
                    <td><StageBadge stageId={o.stage}/></td>
                    <td>{fmtDateShort(o.createdAt)}</td>
                    <td style={overdue ? { color: 'var(--red-600)', fontWeight: 600 } : {}}>
                      {o.dueAt ? fmtDateShort(o.dueAt) : '—'}
                    </td>
                    <td style={{ width: 130 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <div style={{ flex: 1, height: 6, background: 'var(--ink-100)', borderRadius: 99 }}>
                          <div style={{ height: '100%', width: pct + '%', background: 'var(--navy-600)', borderRadius: 99 }}/>
                        </div>
                        <span style={{ fontSize: 11, color: 'var(--ink-500)', minWidth: 32, textAlign: 'right' }}>{done}/{total}</span>
                      </div>
                    </td>
                    <td className="num"><b>{fmtMoney(o.amount, o.currency)}</b></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

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

/* ========== New order modal ========== */
function NewOrderModal({ onClose, onCreated }) {
  const state = useStore();
  const [form, setForm] = useState({
    customerId: state.customers[0]?.id || '',
    type: 'visa',
    country: 'KR',
    title: '',
    amount: state.pricing[0]?.price || 0,
    dueAt: '',
  });
  const [creatingCustomer, setCreatingCustomer] = useState(false);
  const [newCust, setNewCust] = useState({ name: '', phone: '', email: '', address: '' });

  // Auto-fill title + amount when country changes
  useEffect(() => {
    if (form.type === 'visa' && form.country) {
      const p = state.pricing.find(x=>x.code===form.country);
      if (p) setForm(f => ({ ...f, title: p.name + ' Visa', amount: p.price }));
    }
  }, [form.type, form.country]);

  const handleCreate = () => {
    let customerId = form.customerId;
    if (creatingCustomer) {
      if (!newCust.name.trim()) { alert('Please enter customer name'); return; }
      const c = window.PVStore.addCustomer(newCust);
      customerId = c.id;
    }
    if (!customerId) { alert('Please select a customer'); return; }
    if (!form.title.trim()) { alert('Please enter a title'); return; }
    const o = window.PVStore.addOrder({
      customerId,
      type: form.type,
      country: form.type === 'visa' ? form.country : null,
      title: form.title,
      amount: parseFloat(form.amount) || 0,
      currency: 'USD',
      stage: 'inquiry',
      dueAt: form.dueAt ? new Date(form.dueAt).getTime() : null,
    });
    onCreated && onCreated(o.id);
  };

  return (
    <Modal
      open
      onClose={onClose}
      title="New order"
      size="md"
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={handleCreate}>Create order</button>
      </>}
    >
      <div className="row-gap">
        <div className="field">
          <label>Customer</label>
          {!creatingCustomer ? (
            <div style={{ display: 'flex', gap: 8 }}>
              <select value={form.customerId} onChange={e=>setForm({...form, customerId: e.target.value})} style={{ flex: 1 }}>
                <option value="">— Select customer —</option>
                {state.customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
              <button className="btn" onClick={() => setCreatingCustomer(true)}>
                <Icon name="plus" size={12}/> New
              </button>
            </div>
          ) : (
            <div className="card" style={{ background: 'var(--navy-50)', borderColor: 'var(--navy-100)' }}>
              <div className="card-body">
                <div className="form-row two">
                  <div className="field">
                    <label>Name</label>
                    <input value={newCust.name} onChange={e=>setNewCust({...newCust, name: e.target.value})} placeholder="Full name"/>
                  </div>
                  <div className="field">
                    <label>Phone</label>
                    <input value={newCust.phone} onChange={e=>setNewCust({...newCust, phone: e.target.value})} placeholder="+856 20 …"/>
                  </div>
                </div>
                <div className="form-row two" style={{ marginTop: 10 }}>
                  <div className="field">
                    <label>Email</label>
                    <input value={newCust.email} onChange={e=>setNewCust({...newCust, email: e.target.value})}/>
                  </div>
                  <div className="field">
                    <label>Address</label>
                    <input value={newCust.address} onChange={e=>setNewCust({...newCust, address: e.target.value})}/>
                  </div>
                </div>
                <button className="btn ghost sm" onClick={() => setCreatingCustomer(false)} style={{ marginTop: 10 }}>
                  ← Select existing instead
                </button>
              </div>
            </div>
          )}
        </div>

        <div className="form-row two">
          <div className="field">
            <label>Service type</label>
            <select value={form.type} onChange={e=>setForm({...form, type: e.target.value})}>
              <option value="visa">Visa application</option>
              <option value="translation">Document translation</option>
              <option value="consulting">Consulting</option>
            </select>
          </div>
          {form.type === 'visa' ? (
            <div className="field">
              <label>Destination country</label>
              <select value={form.country} onChange={e=>setForm({...form, country: e.target.value})}>
                {state.pricing.map(p => <option key={p.code} value={p.code}>{p.flag} {p.name} — ${p.price}</option>)}
              </select>
            </div>
          ) : (
            <div className="field">
              <label>Title</label>
              <input value={form.title} onChange={e=>setForm({...form, title: e.target.value})} placeholder="e.g. Birth certificate translation"/>
            </div>
          )}
        </div>

        {form.type === 'visa' && (
          <div className="field">
            <label>Title</label>
            <input value={form.title} onChange={e=>setForm({...form, title: e.target.value})}/>
          </div>
        )}

        <div className="form-row two">
          <div className="field">
            <label>Amount (USD)</label>
            <input type="number" value={form.amount} onChange={e=>setForm({...form, amount: e.target.value})}/>
          </div>
          <div className="field">
            <label>Due date</label>
            <input type="date" value={form.dueAt} onChange={e=>setForm({...form, dueAt: e.target.value})}/>
          </div>
        </div>

        {form.type === 'visa' && (
          <div className="field">
            <div className="hint">
              <Icon name="check" size={12} style={{ verticalAlign: 'middle' }}/> A default {state.docTemplate.length}-item document checklist will be created automatically.
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}

/* ========== Order detail ========== */
function OrderDetail({ orderId, onBack, onNav }) {
  const state = useStore();
  const order = state.orders.find(o => o.id === orderId);
  const [tab, setTab] = useState('checklist');
  const [noteText, setNoteText] = useState('');
  const [showInvoiceFor, setShowInvoiceFor] = useState(null);

  if (!order) {
    return (
      <div className="empty">
        <h4>Order not found</h4>
        <button className="btn primary" onClick={onBack}>← Back to orders</button>
      </div>
    );
  }

  const cust = customerById(order.customerId);
  const files = window.PVStore.getFiles(order.id);
  const checklist = order.checklist || [];
  const done = checklist.filter(c=>c.done).length;
  const linkedInvoice = order.invoiceId && state.invoices.find(i=>i.id===order.invoiceId);

  const toggleCheck = (idx) => {
    const next = checklist.map((c,i) => i===idx ? {...c, done: !c.done} : c);
    window.PVStore.setOrderChecklist(order.id, next);
  };
  const addCheckItem = (label) => {
    if (!label.trim()) return;
    window.PVStore.setOrderChecklist(order.id, [...checklist, { label, done: false }]);
  };
  const removeCheckItem = (idx) => {
    window.PVStore.setOrderChecklist(order.id, checklist.filter((_,i)=>i!==idx));
  };

  const handleFiles = async (fileList) => {
    for (const file of fileList) {
      await window.PVStore.addFile(order.id, {
        id: uid(),
        name: file.name,
        size: file.size,
        type: file.type,
        blob: file,
      });
    }
  };

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

      <div className="detail-head">
        <div className="h-left">
          <div className="hstack" style={{ marginBottom: 4 }}>
            <span style={{ fontSize: 28 }}>{order.type === 'visa' ? countryFlag(order.country) : '📝'}</span>
            <h1>{order.title}</h1>
          </div>
          <div className="h-meta">
            <span>{order.orderNo}</span>
            <span>·</span>
            <span>Created {fmtDate(order.createdAt)}</span>
            {order.dueAt && <>
              <span>·</span>
              <span>Due {fmtDate(order.dueAt)}</span>
            </>}
          </div>
        </div>
        <div className="hstack">
          <select
            value={order.stage}
            onChange={(e) => window.PVStore.updateOrder(order.id, { stage: e.target.value })}
            style={{
              background: '#fff', border: '1px solid var(--ink-200)', borderRadius: 7,
              padding: '8px 12px', fontWeight: 600, fontSize: 13, outline: 'none'
            }}
          >
            {state.stages.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
          </select>
        </div>
      </div>

      {/* Top metadata grid */}
      <div className="split" style={{ marginBottom: 18 }}>
        <div className="card">
          <div className="card-header"><h3>Order details</h3></div>
          <div className="card-body">
            <div className="form-row two">
              <div>
                <div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Client</div>
                <div style={{ fontWeight: 600 }}>
                  <a onClick={()=>onNav('customers', { customerId: cust?.id })} style={{ color: 'var(--navy-700)', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2 }}>
                    {cust ? cust.name : '—'}
                  </a>
                </div>
                {cust && <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 2 }}>
                  {cust.phone} {cust.email && <span> · {cust.email}</span>}
                </div>}
              </div>
              <div>
                <div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Service</div>
                <div style={{ fontWeight: 600 }}>
                  {order.type === 'visa' ? `${countryName(order.country)} Visa` : order.type === 'translation' ? 'Translation' : 'Consulting'}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Amount</div>
                <div style={{ fontWeight: 600, fontSize: 18 }}>{fmtMoney(order.amount, order.currency)}</div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Progress</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <div style={{ flex: 1, height: 8, background: 'var(--ink-100)', borderRadius: 99 }}>
                    <div style={{ height: '100%', width: (checklist.length ? Math.round(done/checklist.length*100) : 0) + '%', background: 'var(--navy-600)', borderRadius: 99 }}/>
                  </div>
                  <span style={{ fontSize: 12, fontWeight: 600 }}>{done}/{checklist.length}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-header"><h3>Invoice</h3></div>
          <div className="card-body">
            {linkedInvoice ? (
              <div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span className="order-num" style={{ fontSize: 13 }}>{linkedInvoice.no}</span>
                  <span className={`badge ${linkedInvoice.status === 'paid' ? 'green' : linkedInvoice.status === 'sent' ? 'amber' : 'slate'}`}>{linkedInvoice.status}</span>
                </div>
                <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>{fmtMoney(linkedInvoice.total, linkedInvoice.currency)}</div>
                <button className="btn sm" onClick={() => onNav('invoices', { invoiceId: linkedInvoice.id })}>
                  <Icon name="eye" size={12}/> View invoice
                </button>
              </div>
            ) : (
              <div>
                <p style={{ fontSize: 13, color: 'var(--ink-500)', margin: '0 0 10px' }}>No invoice yet for this order.</p>
                <button className="btn primary sm" onClick={() => setShowInvoiceFor(order)}>
                  <Icon name="plus" size={12}/> Create invoice
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="detail-tabs">
        <button className={tab==='checklist' ? 'active' : ''} onClick={() => setTab('checklist')}>
          <Icon name="check" size={14}/> Document checklist <span className="count">{done}/{checklist.length}</span>
        </button>
        <button className={tab==='files' ? 'active' : ''} onClick={() => setTab('files')}>
          <Icon name="file" size={14}/> Files <span className="count">{files.length}</span>
        </button>
        <button className={tab==='notes' ? 'active' : ''} onClick={() => setTab('notes')}>
          <Icon name="edit" size={14}/> Notes <span className="count">{(order.notes||[]).length}</span>
        </button>
      </div>

      {tab === 'checklist' && (
        <div>
          <div className="checklist">
            {checklist.length === 0 && <div className="empty"><h4>No checklist yet</h4><p>Add items below.</p></div>}
            {checklist.map((c, i) => (
              <div key={i} className={`checklist-item ${c.done ? 'done' : ''}`}>
                <div className="ci-check" onClick={() => toggleCheck(i)}>
                  {c.done && <Icon name="check" size={13}/>}
                </div>
                <div className="ci-label">{c.label}</div>
                <button className="btn ghost icon" onClick={() => removeCheckItem(i)} title="Remove">
                  <Icon name="trash" size={13}/>
                </button>
              </div>
            ))}
          </div>
          <AddChecklistItem onAdd={addCheckItem}/>
        </div>
      )}

      {tab === 'files' && (
        <div>
          <FileDropzone onFiles={handleFiles}/>
          {files.length === 0 ? (
            <div className="empty"><h4>No files yet</h4><p>Drag files into the area above, or click to upload.</p></div>
          ) : (
            <div className="file-grid">
              {files.map(f => (
                <div className="file-card" key={f.id}>
                  <div className="f-preview">
                    {f.type && f.type.startsWith('image/') ? (
                      <img src={f.dataUrl} alt={f.name}/>
                    ) : (
                      <div style={{ textAlign: 'center', color: 'var(--ink-400)' }}>
                        <Icon name="file" size={32}/>
                        <div style={{ fontSize: 10, marginTop: 4, textTransform: 'uppercase' }}>
                          {(f.name.split('.').pop() || 'file').slice(0,5)}
                        </div>
                      </div>
                    )}
                  </div>
                  <div className="f-info">
                    <div className="f-name" title={f.name}>{f.name}</div>
                    <div className="f-meta">
                      <span>{(f.size/1024).toFixed(1)} KB</span>
                      <span>{fmtDateShort(f.uploadedAt)}</span>
                    </div>
                  </div>
                  <div className="f-actions">
                    <button onClick={() => {
                      const a = document.createElement('a');
                      a.href = f.dataUrl;
                      a.download = f.name;
                      a.click();
                    }}><Icon name="download" size={12}/> Download</button>
                    <button onClick={() => {
                      if (confirm('Delete this file?')) window.PVStore.deleteFile(order.id, f.id);
                    }}><Icon name="trash" size={12}/> Delete</button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {tab === 'notes' && (
        <div>
          <div className="card" style={{ marginBottom: 14 }}>
            <div className="card-body">
              <div className="field">
                <label>Add a note</label>
                <textarea
                  value={noteText}
                  onChange={e=>setNoteText(e.target.value)}
                  placeholder="e.g. Called client, awaiting bank statement"
                  rows="3"
                />
              </div>
              <div style={{ marginTop: 10, display: 'flex', justifyContent: 'flex-end' }}>
                <button
                  className="btn primary sm"
                  onClick={() => {
                    if (noteText.trim()) {
                      window.PVStore.addOrderNote(order.id, noteText.trim());
                      setNoteText('');
                    }
                  }}
                >Save note</button>
              </div>
            </div>
          </div>
          {(order.notes||[]).length === 0 && <div className="empty"><h4>No notes yet</h4></div>}
          {(order.notes||[]).map(n => (
            <div className="note-item" key={n.id}>
              <div className="nt-head">
                <span>{fmtDateTime(n.ts)}</span>
                <button className="btn ghost icon" onClick={() => window.PVStore.deleteOrderNote(order.id, n.id)}>
                  <Icon name="trash" size={12}/>
                </button>
              </div>
              <div className="nt-text">{n.text}</div>
            </div>
          ))}
        </div>
      )}

      {showInvoiceFor && (
        <window.NewInvoiceModal
          fromOrder={showInvoiceFor}
          onClose={() => setShowInvoiceFor(null)}
          onCreated={(invId) => {
            window.PVStore.updateOrder(order.id, { invoiceId: invId });
            window.PVStore.updateInvoice(invId, { orderId: order.id });
            setShowInvoiceFor(null);
          }}
        />
      )}
    </div>
  );
}

function AddChecklistItem({ onAdd }) {
  const [val, setVal] = useState('');
  return (
    <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
      <input
        value={val}
        onChange={e=>setVal(e.target.value)}
        onKeyDown={e=>{ if (e.key === 'Enter') { onAdd(val); setVal(''); } }}
        placeholder="Add a document or task…"
        style={{
          flex: 1, padding: '9px 12px', borderRadius: 7,
          border: '1px solid var(--ink-200)', outline: 'none'
        }}
      />
      <button className="btn primary" onClick={() => { onAdd(val); setVal(''); }}>
        <Icon name="plus" size={12}/> Add
      </button>
    </div>
  );
}

function FileDropzone({ onFiles }) {
  const [drag, setDrag] = useState(false);
  const inputRef = useRef();
  return (
    <div
      className={`file-dropzone ${drag ? 'drag' : ''}`}
      onClick={() => inputRef.current?.click()}
      onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
      onDragLeave={() => setDrag(false)}
      onDrop={(e) => {
        e.preventDefault();
        setDrag(false);
        onFiles(Array.from(e.dataTransfer.files));
      }}
    >
      <Icon name="upload" size={24}/>
      <div style={{ marginTop: 8, fontWeight: 600 }}>Drop files here or click to upload</div>
      <div style={{ fontSize: 12, marginTop: 4 }}>Passports, photos, scans, completed forms — anything related to this order.</div>
      <input
        type="file"
        ref={inputRef}
        multiple
        style={{ display: 'none' }}
        onChange={(e) => onFiles(Array.from(e.target.files))}
      />
    </div>
  );
}

window.OrdersView = OrdersView;
window.OrderDetail = OrderDetail;
window.NewOrderModal = NewOrderModal;
