/* global React */
const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS, useRef: useRefS } = React;

// =============================================================================
// PHOTO SLOTS — slot_key → { label, recommended size, page }
// =============================================================================
window.PHOTO_SLOTS = [
  { key: 'hero-photo',        label: 'Homepage Hero',      page: 'Homepage', size: '800 × 1000 px' },
  { key: 'press-on-set-01',   label: 'Press-On Teaser 1',  page: 'Homepage', size: '480 × 560 px' },
  { key: 'press-on-set-02',   label: 'Press-On Teaser 2',  page: 'Homepage', size: '480 × 560 px' },
  { key: 'gallery-1',         label: 'Gallery 1 — Aurora Chrome',  page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-2',         label: 'Gallery 2 — Hand-painted',    page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-3',         label: 'Gallery 3 — Micro French',    page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-4',         label: 'Gallery 4 — Pearl Drop',      page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-5',         label: 'Gallery 5 — Cat Eye',         page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-6',         label: 'Gallery 6 — Butter Nude',     page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-7',         label: 'Gallery 7 — Cherry Blossom',  page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-8',         label: 'Gallery 8 — Mirror Chrome',   page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-9',         label: 'Gallery 9 — Lavender French', page: 'Gallery', size: '400 × 533 px' },
  { key: 'gallery-10',        label: 'Gallery 10 — Bow Charms',     page: 'Gallery', size: '400 × 533 px' },
];

// =============================================================================
// PHOTOS
// =============================================================================
window.PhotosSection = function PhotosSection() {
  const [photos, setPhotos] = useStateS({});
  const [loading, setLoading] = useStateS(true);
  const [uploadingKey, setUploadingKey] = useStateS(null);
  const [err, setErr] = useStateS('');

  function load() {
    setLoading(true);
    window.LQ.request('/photos').then((p) => { setPhotos(p || {}); setLoading(false); });
  }
  useEffectS(load, []);

  async function upload(slotKey, file, label) {
    setUploadingKey(slotKey); setErr('');
    try {
      await window.LQ.uploadPhoto(slotKey, file, label);
      load();
    } catch (e) {
      setErr(e.message);
    } finally {
      setUploadingKey(null);
    }
  }

  async function remove(slotKey) {
    if (!confirm('Remove this photo?')) return;
    await window.LQ.request(`/photos/${slotKey}`, { method: 'DELETE' });
    load();
  }

  const grouped = useMemoS(() => {
    const g = {};
    window.PHOTO_SLOTS.forEach((s) => { (g[s.page] = g[s.page] || []).push(s); });
    return g;
  }, []);

  if (loading) return <div className="admin-loading">Loading…</div>;

  return (
    <>
      <p className="admin-section-intro">Upload real photos to replace placeholders on the public site. Use JPG, PNG, or WebP — max 8 MB. Aim for the recommended size for crisp display.</p>
      {err && <div className="admin-auth-msg err">{err}</div>}

      {Object.entries(grouped).map(([page, slots]) => (
        <div className="admin-panel" key={page}>
          <div className="admin-panel-head">
            <h3>{page}</h3>
            <span className="admin-chip">{slots.filter((s) => photos[s.key]).length} / {slots.length} uploaded</span>
          </div>
          <div className="admin-photo-grid">
            {slots.map((s) => {
              const p = photos[s.key];
              return (
                <div key={s.key} className={`admin-photo-card ${p ? 'has-image' : ''}`}>
                  <div className="admin-photo-thumb" style={p ? { backgroundImage: `url(../${p.file_path})` } : null}>
                    {!p && <div className="admin-photo-empty">No image</div>}
                  </div>
                  <div className="admin-photo-info">
                    <div className="admin-photo-label">{s.label}</div>
                    <div className="admin-photo-size">{s.size}</div>
                    <div className="admin-photo-actions">
                      <label className="admin-btn admin-btn-ghost admin-btn-sm">
                        {uploadingKey === s.key ? 'Uploading…' : (p ? 'Replace' : 'Upload')}
                        <input type="file" accept="image/jpeg,image/png,image/webp" style={{ display: 'none' }}
                               onChange={(e) => e.target.files[0] && upload(s.key, e.target.files[0], s.label)} />
                      </label>
                      {p && <button className="admin-btn admin-btn-ghost admin-btn-sm admin-btn-danger" onClick={() => remove(s.key)}>×</button>}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      ))}
    </>
  );
};

// =============================================================================
// SHOP (Press-on products)
// =============================================================================
const CATEGORIES = ['Chrome', 'Florals', 'French', 'Glitter', '3D Charms', 'Minimal'];
const SHAPES = ['Almond', 'Coffin', 'Stiletto', 'Square', 'Short Square', 'Oval', 'Short Oval', 'Ballerina'];
const TAG_OPTIONS = ['Bestseller', 'New', 'Bridal', 'Hand-painted'];

window.ShopSection = function ShopSection() {
  const [list, setList] = useStateS([]);
  const [loading, setLoading] = useStateS(true);
  const [editing, setEditing] = useStateS(null);
  const [adding, setAdding] = useStateS(false);

  function load() {
    setLoading(true);
    window.LQ.request('/products').then((r) => { setList(r || []); setLoading(false); });
  }
  useEffectS(load, []);

  async function del(id) {
    if (!confirm('Deactivate this product?')) return;
    await window.LQ.request(`/products/${id}`, { method: 'DELETE' });
    load();
  }

  if (loading) return <div className="admin-loading">Loading…</div>;

  return (
    <>
      <div className="admin-toolbar">
        <p className="admin-section-intro" style={{ margin: 0 }}>{list.length} products active.</p>
        <button className="admin-btn admin-btn-primary" onClick={() => setAdding(true)}>+ Add Product</button>
      </div>

      <div className="admin-table-wrap">
        <table className="admin-table">
          <thead>
            <tr><th>Photo</th><th>Name</th><th>Category</th><th>Shape</th><th>Price</th><th>Stock</th><th>Tags</th><th>Actions</th></tr>
          </thead>
          <tbody>
            {list.map((p) => (
              <tr key={p.id}>
                <td>
                  <div className="admin-thumb" style={p.photo_path ? { backgroundImage: `url(../${p.photo_path})` } : null} />
                </td>
                <td><strong>{p.name}</strong></td>
                <td>{p.category}</td>
                <td>{p.shape}</td>
                <td>{window.LQ_fmtINR(p.price)}</td>
                <td className={p.stock <= p.low_stock_alert ? 'admin-low-stock' : ''}>{p.stock}</td>
                <td>{(p.tags || []).map((t) => <span key={t} className="admin-chip">{t}</span>)}</td>
                <td>
                  <div className="admin-row-actions">
                    <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setEditing(p)}>Edit</button>
                    <button className="admin-btn admin-btn-ghost admin-btn-sm admin-btn-danger" onClick={() => del(p.id)}>×</button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {(editing || adding) && (
        <window.ProductModal
          product={editing}
          onClose={() => { setEditing(null); setAdding(false); }}
          onSaved={() => { setEditing(null); setAdding(false); load(); }}
        />
      )}
    </>
  );
};

window.ProductModal = function ProductModal({ product, onClose, onSaved }) {
  const isEdit = !!product;
  const [form, setForm] = useStateS({
    name: product?.name || '',
    category: product?.category || CATEGORIES[0],
    shape: product?.shape || SHAPES[0],
    price: product?.price || '',
    purchase_price: product?.purchase_price || '',
    stock: product?.stock || 0,
    low_stock_alert: product?.low_stock_alert || 3,
    tags: product?.tags || [],
    photo_path: product?.photo_path || '',
    is_active: product?.is_active ?? true,
  });
  const [saving, setSaving] = useStateS(false);
  const [uploading, setUploading] = useStateS(false);
  const [err, setErr] = useStateS('');

  function set(k, v) { setForm((f) => ({ ...f, [k]: v })); }
  function toggleTag(t) {
    setForm((f) => ({ ...f, tags: f.tags.includes(t) ? f.tags.filter((x) => x !== t) : [...f.tags, t] }));
  }

  async function uploadPhoto(file) {
    setUploading(true); setErr('');
    try {
      const slotKey = `shop-product-${product?.id || Date.now()}`;
      const r = await window.LQ.uploadPhoto(slotKey, file, form.name || 'Product');
      set('photo_path', r.file_path);
    } catch (e) {
      setErr(e.message);
    } finally {
      setUploading(false);
    }
  }

  async function save(e) {
    e.preventDefault();
    setSaving(true); setErr('');
    try {
      const body = { ...form };
      body.price = Number(body.price);
      body.purchase_price = body.purchase_price === '' ? null : Number(body.purchase_price);
      body.stock = Number(body.stock);
      body.low_stock_alert = Number(body.low_stock_alert);
      if (isEdit) await window.LQ.request(`/products/${product.id}`, { method: 'PATCH', body });
      else await window.LQ.request('/products', { method: 'POST', body });
      onSaved();
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  }

  const margin = (form.price && form.purchase_price) ?
    Math.round(((form.price - form.purchase_price) / form.price) * 100) : null;

  return (
    <div className="admin-modal-overlay" onClick={onClose}>
      <div className="admin-modal admin-modal-wide" onClick={(e) => e.stopPropagation()}>
        <div className="admin-modal-head">
          <h3>{isEdit ? 'Edit Product' : 'Add Product'}</h3>
          <button className="admin-modal-close" onClick={onClose}>×</button>
        </div>
        <form onSubmit={save} className="admin-modal-body">
          <div className="admin-form-grid">
            <div className="admin-form-row-full">
              <label className="admin-label">Name</label>
              <input className="admin-input" required value={form.name} onChange={(e) => set('name', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Category</label>
              <select className="admin-input" value={form.category} onChange={(e) => set('category', e.target.value)}>
                {CATEGORIES.map((c) => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="admin-label">Shape</label>
              <select className="admin-input" value={form.shape} onChange={(e) => set('shape', e.target.value)}>
                {SHAPES.map((s) => <option key={s}>{s}</option>)}
              </select>
            </div>
            <div>
              <label className="admin-label">Price (₹)</label>
              <input className="admin-input" type="number" required value={form.price} onChange={(e) => set('price', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Purchase Price (₹)</label>
              <input className="admin-input" type="number" value={form.purchase_price} onChange={(e) => set('purchase_price', e.target.value)} placeholder="optional" />
            </div>
            <div>
              <label className="admin-label">Stock</label>
              <input className="admin-input" type="number" min="0" value={form.stock} onChange={(e) => set('stock', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Low-stock alert at</label>
              <input className="admin-input" type="number" min="0" value={form.low_stock_alert} onChange={(e) => set('low_stock_alert', e.target.value)} />
            </div>
            {margin !== null && (
              <div className="admin-form-row-full" style={{ background: 'rgba(2,0,73,0.05)', padding: '10px 14px', borderRadius: 4 }}>
                Margin: <strong>{margin}%</strong> ({window.LQ_fmtINR(form.price - form.purchase_price)} per unit)
              </div>
            )}
            <div className="admin-form-row-full">
              <label className="admin-label">Tags</label>
              <div className="admin-chip-toggle-row">
                {TAG_OPTIONS.map((t) => (
                  <button type="button" key={t}
                          className={`admin-chip-btn ${form.tags.includes(t) ? 'active' : ''}`}
                          onClick={() => toggleTag(t)}>{t}</button>
                ))}
              </div>
            </div>
            <div className="admin-form-row-full">
              <label className="admin-label">Photo</label>
              <div className={`admin-upload-zone ${form.photo_path ? 'has-image' : ''}`} style={form.photo_path ? { backgroundImage: `url(../${form.photo_path})` } : null}>
                {!form.photo_path && <div>{uploading ? 'Uploading…' : 'Click to upload'}</div>}
                <input type="file" accept="image/jpeg,image/png,image/webp" onChange={(e) => e.target.files[0] && uploadPhoto(e.target.files[0])} />
              </div>
            </div>
            <div className="admin-form-row-full">
              <label className="admin-toggle-row">
                <input type="checkbox" checked={form.is_active} onChange={(e) => set('is_active', e.target.checked)} />
                <span>Active (visible on shop)</span>
              </label>
            </div>
          </div>
          {err && <div className="admin-auth-msg err">{err}</div>}
          <div className="admin-modal-foot">
            <button type="button" className="admin-btn admin-btn-ghost" onClick={onClose}>Cancel</button>
            <button type="submit" className="admin-btn admin-btn-primary" disabled={saving}>{saving ? 'Saving…' : (isEdit ? 'Save changes' : 'Add product')}</button>
          </div>
        </form>
      </div>
    </div>
  );
};

// =============================================================================
// INVENTORY (compact view, inline editing)
// =============================================================================
window.InventorySection = function InventorySection() {
  const [list, setList] = useStateS([]);
  const [loading, setLoading] = useStateS(true);

  function load() {
    setLoading(true);
    window.LQ.request('/products').then((r) => { setList(r || []); setLoading(false); });
  }
  useEffectS(load, []);

  async function update(id, patch) {
    await window.LQ.request(`/products/${id}`, { method: 'PATCH', body: patch });
    load();
  }

  if (loading) return <div className="admin-loading">Loading…</div>;

  return (
    <>
      <p className="admin-section-intro">Adjust stock and pricing inline. Stock auto-decrements when an order ships.</p>
      <div className="admin-table-wrap">
        <table className="admin-table">
          <thead>
            <tr><th>Name</th><th>Cost</th><th>Price</th><th>Margin</th><th>Stock</th><th>Alert at</th></tr>
          </thead>
          <tbody>
            {list.map((p) => {
              const margin = (p.price && p.purchase_price) ? Math.round(((p.price - p.purchase_price) / p.price) * 100) : '—';
              return (
                <tr key={p.id} className={p.stock <= p.low_stock_alert ? 'admin-row-warn' : ''}>
                  <td><strong>{p.name}</strong><div className="admin-cell-sub">{p.category}</div></td>
                  <td><input className="admin-input admin-input-sm" type="number" defaultValue={p.purchase_price ?? ''} onBlur={(e) => update(p.id, { purchase_price: e.target.value === '' ? null : Number(e.target.value) })} /></td>
                  <td><input className="admin-input admin-input-sm" type="number" defaultValue={p.price} onBlur={(e) => update(p.id, { price: Number(e.target.value) })} /></td>
                  <td>{typeof margin === 'number' ? margin + '%' : margin}</td>
                  <td>
                    <div className="admin-stepper">
                      <button onClick={() => update(p.id, { stock: Math.max(0, p.stock - 1) })}>−</button>
                      <input className="admin-input admin-input-sm" type="number" min="0" defaultValue={p.stock} onBlur={(e) => update(p.id, { stock: Number(e.target.value) })} />
                      <button onClick={() => update(p.id, { stock: p.stock + 1 })}>+</button>
                    </div>
                  </td>
                  <td><input className="admin-input admin-input-sm" type="number" min="0" defaultValue={p.low_stock_alert} onBlur={(e) => update(p.id, { low_stock_alert: Number(e.target.value) })} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

// =============================================================================
// SHIPPING (orders + provider toggle)
// =============================================================================
window.ShippingSection = function ShippingSection() {
  const [orders, setOrders] = useStateS([]);
  const [shipping, setShipping] = useStateS(null);
  const [loading, setLoading] = useStateS(true);

  function load() {
    setLoading(true);
    Promise.all([
      window.LQ.request('/orders'),
      window.LQ.request('/settings/shipping').catch(() => ({ provider: 'manual' })),
    ]).then(([o, s]) => {
      setOrders(o || []);
      setShipping(s || { provider: 'manual' });
      setLoading(false);
    });
  }
  useEffectS(load, []);

  async function setStatus(id, status) {
    await window.LQ.request(`/orders/${id}`, { method: 'PATCH', body: { status } });
    load();
  }

  async function printLabel(o) {
    if (shipping.provider === 'manual') {
      window.LQ_printManualLabel(o, shipping);
      await window.LQ.request(`/orders/${o.id}`, { method: 'PATCH', body: { label_printed: true } });
      load();
      return;
    }
    // Shiprocket flow — placeholder until live integration
    alert(`Shiprocket label for ${o.order_code} will be fetched from API once credentials are saved + tested.`);
    await window.LQ.request(`/orders/${o.id}`, { method: 'PATCH', body: { label_printed: true } });
    load();
  }

  async function saveShipping() {
    await window.LQ.request('/settings/shipping', { method: 'PUT', body: shipping });
    alert('Shipping settings saved.');
  }

  function set(k, v) { setShipping({ ...shipping, [k]: v }); }

  if (loading) return <div className="admin-loading">Loading…</div>;

  return (
    <>
      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Shipping Provider</h3></div>
        <div className="admin-form-grid">
          <div className="admin-form-row-full">
            <div className="admin-radio-row">
              <label><input type="radio" name="prov" checked={shipping.provider === 'manual'}     onChange={() => set('provider', 'manual')}     /> Manual (you ship yourself)</label>
              <label><input type="radio" name="prov" checked={shipping.provider === 'shiprocket'} onChange={() => set('provider', 'shiprocket')} /> Shiprocket</label>
            </div>
          </div>

          {shipping.provider === 'manual' && <>
            <div className="admin-form-row-full">
              <p className="admin-section-intro" style={{ marginBottom: 0 }}>
                Used as the <strong>FROM</strong> address on every shipping label you print.
                Update this once — it appears on every label.
              </p>
            </div>
            <div>
              <label className="admin-label">Sender / Business Name</label>
              <input className="admin-input" value={shipping.from_name || ''} onChange={(e) => set('from_name', e.target.value)} placeholder="Lacquery Nails" />
            </div>
            <div>
              <label className="admin-label">Sender Phone</label>
              <input className="admin-input" value={shipping.from_phone || ''} onChange={(e) => set('from_phone', e.target.value)} placeholder="+91 83174 51779" />
            </div>
            <div className="admin-form-row-full">
              <label className="admin-label">Sender Address</label>
              <textarea className="admin-input" rows="2" value={shipping.from_address || ''} onChange={(e) => set('from_address', e.target.value)} placeholder="Studio address with door no., street, landmark" />
            </div>
            <div>
              <label className="admin-label">City</label>
              <input className="admin-input" value={shipping.from_city || ''} onChange={(e) => set('from_city', e.target.value)} placeholder="Bengaluru" />
            </div>
            <div>
              <label className="admin-label">State</label>
              <input className="admin-input" value={shipping.from_state || ''} onChange={(e) => set('from_state', e.target.value)} placeholder="Karnataka" />
            </div>
            <div>
              <label className="admin-label">Pincode</label>
              <input className="admin-input" value={shipping.from_pincode || ''} onChange={(e) => set('from_pincode', e.target.value)} placeholder="560021" />
            </div>
            <div>
              <label className="admin-label">GSTIN (optional)</label>
              <input className="admin-input" value={shipping.from_gstin || ''} onChange={(e) => set('from_gstin', e.target.value)} placeholder="29AAAAA0000A1Z5" />
            </div>
          </>}

          {shipping.provider === 'shiprocket' && <>
            <div className="admin-form-row-full">
              <p className="admin-section-intro" style={{ marginBottom: 0 }}>
                Shiprocket fetches labels + tracking from their API. Get credentials at app.shiprocket.in → Settings → API.
              </p>
            </div>
            <div>
              <label className="admin-label">Shiprocket Email</label>
              <input className="admin-input" value={shipping.shiprocket_email || ''} onChange={(e) => set('shiprocket_email', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Password</label>
              <input className="admin-input" type="password" value={shipping.shiprocket_password || ''} onChange={(e) => set('shiprocket_password', e.target.value)} />
            </div>
          </>}

          <div className="admin-form-row-full">
            <button className="admin-btn admin-btn-primary" onClick={saveShipping}>Save provider settings</button>
          </div>
        </div>
      </div>

      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Orders to Fulfil</h3><span className="admin-chip">{orders.filter((o) => ['pending','processing'].includes(o.status)).length} pending</span></div>
        {orders.length === 0 ? <div className="admin-empty-mini">No orders yet.</div> :
         <div className="admin-table-wrap">
           <table className="admin-table">
             <thead><tr><th>Code</th><th>Customer</th><th>Product</th><th>Total</th><th>Status</th><th>Label</th><th>Actions</th></tr></thead>
             <tbody>
               {orders.map((o) => (
                 <tr key={o.id}>
                   <td><strong>{o.order_code}</strong></td>
                   <td><div>{o.customer_name}</div><div className="admin-cell-sub">{o.customer_mobile}</div></td>
                   <td>{o.product_name}{o.quantity > 1 && ` ×${o.quantity}`}</td>
                   <td>{window.LQ_fmtINR(o.total)}</td>
                   <td><span className={`admin-badge ${o.status}`}>{o.status}</span></td>
                   <td>{o.label_printed ? <span className="admin-chip green">Printed</span> : <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => printLabel(o)}>Print</button>}</td>
                   <td>
                     <div className="admin-row-actions">
                       {o.status === 'pending'    && <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setStatus(o.id, 'processing')}>Process</button>}
                       {o.status === 'processing' && <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setStatus(o.id, 'shipped')}>Ship</button>}
                       {o.status === 'shipped'    && <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setStatus(o.id, 'delivered')}>Delivered</button>}
                       {!['cancelled','delivered'].includes(o.status) && <button className="admin-btn admin-btn-ghost admin-btn-sm admin-btn-danger" onClick={() => setStatus(o.id, 'cancelled')}>Cancel</button>}
                     </div>
                   </td>
                 </tr>
               ))}
             </tbody>
           </table>
         </div>
        }
      </div>
    </>
  );
};
