// pages/customer-portal.jsx — addresses, order detail, profile, help, rinpo page

function AddressesPage() {
  const store = useStore();
  if (!store.state.user) return <AccountPage />;
  const [rows, setRows] = React.useState(() => window.CustomerAccount.listAddresses());
  const [form, setForm] = React.useState({ name: '', phone: '', address: '', city: '', state: 'Kerala', pincode: '', isDefault: false });
  const [err, setErr] = React.useState('');
  const refresh = () => setRows(window.CustomerAccount.listAddresses());
  const save = (e) => {
    e.preventDefault();
    setErr('');
    try {
      window.CustomerAccount.upsertAddress(form);
      setForm({ name: '', phone: '', address: '', city: '', state: 'Kerala', pincode: '', isDefault: false });
      refresh();
    } catch (ex) {
      setErr(ex.message || 'Could not save address');
    }
  };
  return (
    <main className="container" style={{ paddingBlock: 48, maxWidth: 720 }}>
      <div className="crumb"><a href="#/account">Account</a><span className="sep">/</span><span className="here">Addresses</span></div>
      <h1 className="serif" style={{ fontSize: 'var(--fs-display)', marginBlock: 16 }}>Addresses</h1>
      {rows.length === 0 ? (
        <EmptyState icon="map" title="No saved addresses" note="Add an address for faster checkout." />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 28 }}>
          {rows.map((a) => (
            <div key={a.id} style={{ background: 'var(--cream)', borderRadius: 12, padding: 18 }}>
              <div className="spread">
                <strong>{a.name}{a.isDefault ? ' · Default' : ''}</strong>
                <button className="btn btn--ghost btn--sm" onClick={() => { window.CustomerAccount.deleteAddress(a.id); refresh(); }}>Delete</button>
              </div>
              <p style={{ color: 'var(--ink-2)', marginTop: 6, fontSize: '.9rem' }}>
                {a.address}<br />{a.city}, {a.state} {a.pincode}<br />{a.phone}
              </p>
              <button className="btn btn--ghost btn--sm" onClick={() => setForm(Object.assign({}, a))}>Edit</button>
            </div>
          ))}
        </div>
      )}
      <form onSubmit={save} style={{ display: 'flex', flexDirection: 'column', gap: 10, background: 'var(--shell)', border: '1px solid var(--line)', borderRadius: 16, padding: 20 }}>
        <h2 className="serif" style={{ fontSize: '1.3rem' }}>{form.id ? 'Edit address' : 'Add address'}</h2>
        <input className="input" placeholder="Name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
        <input className="input" placeholder="Phone" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value.replace(/\D/g, '').slice(0, 10) })} required />
        <input className="input" placeholder="Address" value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} required />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          <input className="input" placeholder="City" value={form.city} onChange={(e) => setForm({ ...form, city: e.target.value })} required />
          <input className="input" placeholder="State" value={form.state} onChange={(e) => setForm({ ...form, state: e.target.value })} required />
          <input className="input" placeholder="Pincode" value={form.pincode} onChange={(e) => setForm({ ...form, pincode: e.target.value.replace(/\D/g, '').slice(0, 6) })} required />
        </div>
        <label className="check"><input type="checkbox" checked={!!form.isDefault} onChange={(e) => setForm({ ...form, isDefault: e.target.checked })} /><span className="check__box"><Icon name="check" size={12} /></span><span>Set as default</span></label>
        {err && <div style={{ color: 'var(--danger)', fontSize: '.85rem' }}>{err}</div>}
        <button className="btn btn--primary" type="submit">Save address</button>
      </form>
    </main>
  );
}

function OrderDetailPage() {
  const route = useRoute();
  const store = useStore();
  if (!store.state.user) return <AccountPage />;
  const res = window.CustomerAccount.getOrderForViewer(route.params.id, store.state.user);
  if (!res.ok) {
    return (
      <main className="container section">
        <h1 className="serif">Order unavailable</h1>
        <p style={{ color: 'var(--muted)', marginBlock: 12 }}>{res.code === 'FORBIDDEN' ? 'You can only view your own orders.' : 'Order not found.'}</p>
        <a className="btn btn--primary" href="#/account/orders">Back to orders</a>
      </main>
    );
  }
  const o = res.order;
  const reorder = () => {
    (o.lines || []).forEach((l) => {
      store.addToCart(l.productId, l.variant, l.qty || 1);
    });
    HAPRouter.nav('#/cart');
  };
  return (
    <main className="container" style={{ paddingBlock: 48, maxWidth: 820 }}>
      <div className="crumb"><a href="#/account/orders">Orders</a><span className="sep">/</span><span className="here">{o.id}</span></div>
      <h1 className="serif" style={{ fontSize: 'var(--fs-display)', marginBlock: 16 }}>{o.id}</h1>
      <p style={{ color: 'var(--muted)' }}>Status: {o.status} · {new Date(o.placedAt).toLocaleString('en-IN')}</p>
      <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {(o.lines || []).map((l) => (
          <div key={l.productId + l.variant} style={{ display: 'flex', gap: 12, background: 'var(--cream)', padding: 12, borderRadius: 12 }}>
            <div style={{ flex: 1 }}>
              <div className="serif">{(l.product && l.product.name) || l.productId}</div>
              <div style={{ fontSize: '.8rem', color: 'var(--muted)' }}>{l.variant} · qty {l.qty}</div>
            </div>
            <div>{HAP.formatPrice(l.line || (l.unit * l.qty) || 0)}</div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 16 }}>
        <div>Subtotal {HAP.formatPrice(o.subtotal)}</div>
        <div>Shipping {o.shipping === 0 ? 'Free' : HAP.formatPrice(o.shipping)}</div>
        <div className="serif" style={{ fontSize: '1.3rem', marginTop: 6 }}>Total {HAP.formatPrice(o.total)}</div>
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 20, flexWrap: 'wrap' }}>
        <a className="btn btn--primary" href={'#/track?o=' + encodeURIComponent(o.id)}>Track</a>
        <button className="btn btn--secondary" onClick={reorder}>Buy again</button>
        <a className="btn btn--ghost" href="#/help">Returns help</a>
      </div>
      <h3 className="serif" style={{ marginTop: 28, marginBottom: 10 }}>Timeline</h3>
      <ul style={{ paddingLeft: 18 }}>
        {(o.timeline || []).map((t, i) => (
          <li key={i} style={{ marginBottom: 6 }}>{t.status} · {new Date(t.at).toLocaleString('en-IN')}</li>
        ))}
      </ul>
      {!o.awb && <p style={{ color: 'var(--muted)', marginTop: 12, fontSize: '.85rem' }}>Tracking will appear once your order is dispatched.</p>}
    </main>
  );
}

function ProfilePage() {
  const store = useStore();
  if (!store.state.user) return <AccountPage />;
  const [name, setName] = React.useState(store.state.user.name || '');
  const [phone, setPhone] = React.useState(store.state.user.phone || '');
  const loadPrefs = () => {
    try {
      const raw = localStorage.getItem('hap.prefs.v1');
      return raw ? JSON.parse(raw) : { marketingOptIn: false, personalization: true };
    } catch (_) {
      return { marketingOptIn: false, personalization: true };
    }
  };
  const [prefs, setPrefs] = React.useState(loadPrefs);
  const savePrefs = (next) => {
    setPrefs(next);
    try { localStorage.setItem('hap.prefs.v1', JSON.stringify(next)); } catch (_) {}
    const intel = window.OwnerIntelligence && window.OwnerIntelligence.get && window.OwnerIntelligence.get();
    if (intel && typeof intel.storeExplicitPreference === 'function') {
      try {
        intel.storeExplicitPreference({
          scope: 'CUSTOMER',
          subjectId: store.state.user.email || store.state.user.id,
          content: 'Customer preference update',
          structuredData: next,
          source: 'account_preferences',
        });
        if (intel.persist) intel.persist();
      } catch (_) {}
    }
  };
  return (
    <main className="container" style={{ paddingBlock: 48, maxWidth: 560 }}>
      <div className="crumb"><a href="#/account">Account</a><span className="sep">/</span><span className="here">Profile</span></div>
      <h1 className="serif" style={{ fontSize: 'var(--fs-display)', marginBlock: 16 }}>Profile</h1>
      <p style={{ color: 'var(--muted)', marginBottom: 16 }}>Email: {store.state.user.email} (sign-in identifier)</p>
      <div className="field"><label htmlFor="profile-name">Name</label><input id="profile-name" className="input" value={name} onChange={(e) => setName(e.target.value)} /></div>
      <div className="field" style={{ marginTop: 10 }}><label htmlFor="profile-phone">Phone</label><input id="profile-phone" className="input" value={phone} onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 10))} /></div>
      <button className="btn btn--primary" style={{ marginTop: 14 }} onClick={() => { store.updateProfile({ name, phone }); HAPStore.notify('Profile saved'); }}>Save</button>

      <section style={{ marginTop: 36, paddingTop: 24, borderTop: '1px solid var(--line)' }}>
        <h2 className="serif" style={{ fontSize: '1.4rem', marginBottom: 12 }}>Preferences</h2>
        <p style={{ fontSize: '.85rem', color: 'var(--muted)', marginBottom: 14 }}>Saved locally{window.OwnerIntelligence ? ' and shared with personalization when available' : ''}.</p>
        <label className="check" style={{ display: 'flex', gap: 10, marginBottom: 10 }}>
          <input type="checkbox" checked={!!prefs.marketingOptIn}
                 onChange={(e) => savePrefs({ ...prefs, marketingOptIn: e.target.checked })} />
          <span>Marketing emails & offers</span>
        </label>
        <label className="check" style={{ display: 'flex', gap: 10 }}>
          <input type="checkbox" checked={prefs.personalization !== false}
                 onChange={(e) => savePrefs({ ...prefs, personalization: e.target.checked })} />
          <span>Personalized recommendations</span>
        </label>
      </section>

      <p style={{ fontSize: '.78rem', color: 'var(--muted)', marginTop: 16 }}>Local session only — Supabase customer Auth is not enabled in default mode.</p>
    </main>
  );
}

function MyReviewsPage() {
  const store = useStore();
  if (!store.state.user) return <AccountPage />;
  const rows = window.CustomerReviews.myReviews(store.state.user);
  return (
    <main className="container" style={{ paddingBlock: 48 }}>
      <div className="crumb"><a href="#/account">Account</a><span className="sep">/</span><span className="here">Reviews</span></div>
      <h1 className="serif" style={{ fontSize: 'var(--fs-display)', marginBlock: 16 }}>Your reviews</h1>
      {rows.length === 0 ? (
        <EmptyState icon="star" title="No reviews yet" note="After a delivered order, you can review eligible products on the product page." />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {rows.map((r) => (
            <div key={r.id} style={{ background: 'var(--cream)', borderRadius: 12, padding: 16 }}>
              <div className="spread"><strong>Product {r.productId}</strong><span className="tag">{r.status}</span></div>
              <div style={{ marginTop: 6 }}>Rating {r.rating}/5</div>
              <p style={{ color: 'var(--ink-2)', marginTop: 6 }}>{r.content}</p>
            </div>
          ))}
        </div>
      )}
    </main>
  );
}

function HelpPage() {
  return (
    <main className="container" style={{ paddingBlock: 48, maxWidth: 800 }}>
      <h1 className="serif" style={{ fontSize: 'var(--fs-display)' }}>Help & support</h1>
      <p style={{ color: 'var(--ink-2)', marginBlock: 12 }}>Policies and contacts from the live Ambady storefront — we do not invent return guarantees beyond what is published.</p>
      <div style={{ display: 'grid', gap: 12, marginTop: 20 }}>
        {[
          ['Order help', '#/track', 'Track with order number + phone verification'],
          ['Shipping', '#/pages/shipping', 'Shipping policy page'],
          ['Returns', '#/pages/refunds', 'Returns & refunds policy — self-serve returns not enabled'],
          ['Support tickets', '#/account/support', 'Open or view tickets for your orders'],
          ['Payments', '#/pages/contact', 'Contact for payment issues'],
          ['Products', '#/collections', 'Browse catalog'],
          ['WhatsApp', 'https://wa.me/917559907176', 'Chat with Ambady'],
          ['Ask RINPO', '#/phone?tab=chat', 'Catalog & order guidance']
        ].map(([t, h, s]) => (
          <a key={t} href={h} style={{ display: 'block', background: 'var(--cream)', borderRadius: 12, padding: 18 }}>
            <div className="serif" style={{ fontSize: '1.2rem' }}>{t}</div>
            <div style={{ fontSize: '.85rem', color: 'var(--muted)' }}>{s}</div>
          </a>
        ))}
      </div>
    </main>
  );
}

function SupportTicketsPage() {
  const store = useStore();
  if (!store.state.user) return <AccountPage />;
  const customerKey = String(store.state.user.email || store.state.user.id || '').toLowerCase();
  const commerceApi = () => {
    if (window.AmbadyCommerce && typeof window.AmbadyCommerce.listCustomerTickets === 'function') {
      return window.AmbadyCommerce;
    }
    return window.AmbadyCommerce && window.AmbadyCommerce.get ? window.AmbadyCommerce.get() : null;
  };
  const [tickets, setTickets] = React.useState([]);
  const [form, setForm] = React.useState({ category: 'order_issue', orderId: '', body: '', subject: '' });
  const [msg, setMsg] = React.useState('');
  const [err, setErr] = React.useState('');
  const refresh = () => {
    const c = commerceApi();
    if (!c || typeof c.listCustomerTickets !== 'function') {
      setTickets([]);
      return;
    }
    try {
      setTickets(c.listCustomerTickets(customerKey) || []);
    } catch (_) {
      setTickets([]);
    }
  };
  React.useEffect(() => { refresh(); }, [customerKey]);
  const submit = (e) => {
    e.preventDefault();
    setErr('');
    setMsg('');
    const c = commerceApi();
    if (!c || typeof c.openTicket !== 'function') {
      setErr('Support tickets are unavailable in this session.');
      return;
    }
    try {
      c.openTicket({
        customerKey: customerKey,
        customerName: store.state.user.name || 'Customer',
        customerEmail: store.state.user.email || null,
        customerPhone: store.state.user.phone || null,
        orderId: form.orderId.trim() || null,
        category: form.category,
        subject: form.subject.trim() || ('Support: ' + form.category),
        body: form.body.trim(),
        authorType: 'customer',
        authorId: customerKey,
      });
      setForm({ category: 'order_issue', orderId: '', body: '', subject: '' });
      setMsg('Ticket submitted.');
      refresh();
    } catch (ex) {
      setErr(ex.message || 'Could not create ticket');
    }
  };
  return (
    <main className="container" style={{ paddingBlock: 48, maxWidth: 720 }}>
      <div className="crumb"><a href="#/account">Account</a><span className="sep">/</span><span className="here">Support tickets</span></div>
      <h1 className="serif" style={{ fontSize: 'var(--fs-display)', marginBlock: 16 }}>Support tickets</h1>
      <p style={{ color: 'var(--muted)', marginBottom: 20 }}>Open tickets for your account only.</p>
      {tickets.length === 0 ? (
        <EmptyState icon="phone" title="No tickets yet" note="Create a ticket below if you need help with an order." />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 28 }}>
          {tickets.map((t) => (
            <div key={t.id} style={{ background: 'var(--cream)', borderRadius: 12, padding: 16 }}>
              <div className="spread">
                <strong>{t.subject || t.id}</strong>
                <span className="tag">{t.status}</span>
              </div>
              <div style={{ fontSize: '.8rem', color: 'var(--muted)', marginTop: 4 }}>
                {t.category}{t.orderId ? ' · ' + t.orderId : ''}
              </div>
              {t.messages && t.messages[0] && (
                <p style={{ marginTop: 8, fontSize: '.9rem', color: 'var(--ink-2)' }}>{t.messages[0].body}</p>
              )}
            </div>
          ))}
        </div>
      )}
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 10, background: 'var(--shell)', border: '1px solid var(--line)', borderRadius: 16, padding: 20 }}>
        <h2 className="serif" style={{ fontSize: '1.3rem' }}>New ticket</h2>
        <label className="field" htmlFor="ticket-category"><span>Category</span>
          <select id="ticket-category" className="input" value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}>
            <option value="order_issue">Order issue</option>
            <option value="damaged">Damaged item</option>
            <option value="refund">Refund request</option>
            <option value="shipping">Shipping</option>
            <option value="other">Other</option>
          </select>
        </label>
        <label className="field" htmlFor="ticket-order"><span>Order ID (optional)</span>
          <input id="ticket-order" className="input" placeholder="APG-…" value={form.orderId} onChange={(e) => setForm({ ...form, orderId: e.target.value })} />
        </label>
        <label className="field" htmlFor="ticket-subject"><span>Subject</span>
          <input id="ticket-subject" className="input" value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })} />
        </label>
        <label className="field" htmlFor="ticket-body"><span>Message</span>
          <textarea id="ticket-body" className="textarea" required value={form.body} onChange={(e) => setForm({ ...form, body: e.target.value })} />
        </label>
        {err && <div style={{ color: 'var(--danger)', fontSize: '.85rem' }}>{err}</div>}
        {msg && <div style={{ color: 'var(--forest)', fontSize: '.85rem' }}>{msg}</div>}
        <button className="btn btn--primary" type="submit">Submit ticket</button>
      </form>
    </main>
  );
}

function CustomerRinpoPage() {
  React.useEffect(() => {
    if (window.RinpoRuntime) {
      window.RinpoRuntime.open({ tab: 'chat', source: 'route_rinpo', surface: 'store' });
    } else {
      HAPRouter.nav('#/phone?tab=chat');
    }
  }, []);

  return (
    <main className="container" style={{ paddingBlock: 24, maxWidth: 720, textAlign: 'center' }}>
      <p className="muted">Opening RINPO…</p>
    </main>
  );
}

window.AddressesPage = AddressesPage;
window.OrderDetailPage = OrderDetailPage;
window.ProfilePage = ProfilePage;
window.MyReviewsPage = MyReviewsPage;
window.HelpPage = HelpPage;
window.SupportTicketsPage = SupportTicketsPage;
window.CustomerRinpoPage = CustomerRinpoPage;
