/* Adeyy app — B1 Billing + SET1-3 Settings (general, team). Live API version. */

/* CardModal is now handled by the Stripe.js modal in api-bridge.js.
   This stub is kept for compatibility with any remaining references. */
function CardModal({ app }) {
  /* Delegate to the Stripe modal immediately */
  React.useEffect(() => {
    app.setCardPrompt(() => {});
  }, []);
  return null;
}

function Billing({ app }) {
  const D = window.AdeyyData;
  const API = window.AdeyyAPI;
  const { links, billing } = app.state;
  const active = links.filter((l) => l.status === 'active').length;

  /* Refresh billing on mount */
  React.useEffect(() => {
    if (app.refreshBilling) app.refreshBilling();
  }, []);

  /* Calculate next invoice date */
  const now = new Date();
  const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
  const nextInvoice = nextMonth.toLocaleString('en-AU', { day: 'numeric', month: 'short' });

  return (
    <div data-screen-label="B1 Billing">
      <div className="apage-head">
        <h1>Billing</h1>
        <span className="meta">Billed through ProDesk · Stripe</span>
      </div>

      <div className="kpis three">
        <Kpi label="Active codes" value={active} sub="Each one redirects live" accent />
        <Kpi label="Monthly cost" value={'$' + active + '.00'} sub="$1.00 per active code, prorated" />
        <Kpi label="Next invoice" value={nextInvoice} sub="Covers this month, adjusted to the day" />
      </div>

      <div className="detail-grid" style={{ gridTemplateColumns: '320px 1fr' }}>
        <div className="dcard">
          <div className="dh"><h2>Card on file</h2></div>
          <div className="db" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {billing.card ? (
              <React.Fragment>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ border: '1px solid var(--border-2)', borderRadius: 4, padding: '6px 10px', fontSize: 12, fontWeight: 700 }}>{billing.card.brand}</span>
                  <span className="slug" style={{ fontSize: 13 }}>···· {billing.card.last4}</span>
                  <span className="mutetext slug" style={{ fontSize: 12 }}>{billing.card.exp}</span>
                </div>
                <button className="abtn abtn-ghost abtn-sm" style={{ alignSelf: 'flex-start' }} onClick={() => app.setCardPrompt(() => {
                  if (app.refreshBilling) app.refreshBilling();
                })}>Update card</button>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <p className="mutetext" style={{ margin: 0, fontSize: 13 }}>No card yet. You will need one to switch your first code on.</p>
                <button className="abtn abtn-primary abtn-sm" style={{ alignSelf: 'flex-start' }} onClick={() => app.setCardPrompt(() => {
                  if (app.refreshBilling) app.refreshBilling();
                })}>Add card</button>
              </React.Fragment>
            )}
            <p className="mutetext" style={{ fontSize: 11.5, margin: 0 }}>
              Activating mid-month charges only the days remaining. Deactivating credits the difference. No hidden maths.
            </p>
          </div>
        </div>

        <div className="dcard">
          <div className="dh"><h2>Invoices</h2></div>
          <div className="db">
            {billing.invoices.length === 0 ? (
              <EmptyState title="No invoices yet." body="Your first invoice arrives the month after your first code goes live." />
            ) : (
              <table className="atable">
                <thead><tr><th>Invoice</th><th>Period</th><th className="r">Amount</th><th>Status</th><th></th></tr></thead>
                <tbody>
                  {billing.invoices.map((inv) => (
                    <tr key={inv.id} style={{ cursor: 'default' }}>
                      <td className="tslug">{inv.id}</td>
                      <td>{inv.period}</td>
                      <td className="tnum">${typeof inv.amount === 'number' ? inv.amount.toFixed(2) : inv.amount}</td>
                      <td><span className="status off" style={{ borderColor: 'transparent', color: 'var(--ink-80)' }}><span className="sdot" style={{ background: 'var(--adeyy)', border: 0 }}></span>Paid</span></td>
                      <td style={{ textAlign: 'right' }}>
                        {inv.pdfUrl ? (
                          <a className="abtn abtn-quiet abtn-sm" href={inv.pdfUrl} target="_blank" rel="noopener noreferrer"><Icon name="download" size={13} /></a>
                        ) : (
                          <button className="abtn abtn-quiet abtn-sm" onClick={() => app.toast('No PDF available yet')}><Icon name="download" size={13} /></button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Settings ---------- */

function Settings({ app, tab }) {
  const [t, setT] = React.useState(tab || 'general');
  return (
    <div data-screen-label="SET1 Settings">
      <div className="apage-head"><h1>Settings</h1></div>
      <div className="settabs">
        <button className={t === 'general' ? 'sel' : ''} onClick={() => setT('general')}>General</button>
        <button className={t === 'team' ? 'sel' : ''} onClick={() => setT('team')}>Team</button>
      </div>
      {t === 'general' ? <SettingsGeneral app={app} /> : <SettingsTeam app={app} />}
    </div>
  );
}

function SettingsGeneral({ app }) {
  const API = window.AdeyyAPI;
  const { vendor, defaultQr } = app.state;
  const [businessName, setBusinessName] = React.useState(vendor.name);
  const [savingName, setSavingName] = React.useState(false);
  const set = (k, v) => app.update((s) => { s.defaultQr = Object.assign({}, s.defaultQr, { [k]: v }); });

  async function saveName() {
    if (!businessName.trim() || businessName.trim() === vendor.name) return;
    setSavingName(true);
    try {
      await API.trpc ? API.trpc('vendor.updateName', { name: businessName.trim() }, 'mutation') : Promise.resolve();
      app.update((s) => { s.vendor.name = businessName.trim(); s.vendor.initials = businessName.trim().slice(0, 2).toUpperCase(); });
      app.toast('Business name updated');
    } catch (e) {
      app.toast('Error: ' + e.message);
    } finally {
      setSavingName(false);
    }
  }

  return (
    <div className="detail-grid" data-screen-label="SET3 Account">
      <div className="dcard">
        <div className="db" style={{ paddingTop: 18, display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 460 }}>
          <div className="afield">
            <label>Business name</label>
            <input className="ainput" value={businessName} onChange={(e) => setBusinessName(e.target.value)}
              onBlur={saveName} onKeyDown={(e) => { if (e.key === 'Enter') saveName(); }} />
            {savingName ? <span className="hint">Saving…</span> : null}
          </div>
          <div className="afield">
            <label>Home country</label>
            <select className="ainput"><option>Australia</option></select>
            <span className="hint">Sets your currency (AUD) and privacy rules (Australian Privacy Principles).</span>
          </div>
          <hr className="divider" style={{ margin: 0 }} />
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Account</div>
            <p className="mutetext" style={{ fontSize: 12.5, margin: '0 0 10px' }}>Sign out of your account.</p>
            <button className="abtn abtn-ghost abtn-sm" onClick={async () => {
              try {
                await window.AdeyyAPI.logout();
                window.location.href = '/login';
              } catch (e) {
                window.location.href = '/login';
              }
            }}>Sign out</button>
          </div>
        </div>
      </div>

      <div className="dcard">
        <div className="dh"><h2>Default QR design</h2><span className="meta">New links start here</span></div>
        <div className="db" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <QrSvg slug="your-link" config={defaultQr} style={{ border: '1px solid var(--border-1)', borderRadius: 4, overflow: 'hidden' }} />
          <div className="ctl" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <Seg value={defaultQr.modules} options={[{ value: 'square', label: 'Square' }, { value: 'rounded', label: 'Rounded' }, { value: 'dots', label: 'Dots' }]} onChange={(v) => set('modules', v)} />
            <Seg value={defaultQr.eyes} options={[{ value: 'square', label: 'Square eyes' }, { value: 'rounded', label: 'Rounded eyes' }]} onChange={(v) => set('eyes', v)} />
          </div>
        </div>
      </div>
    </div>
  );
}

function SettingsTeam({ app }) {
  const API = window.AdeyyAPI;
  const { team, user } = app.state;
  const [inviting, setInviting] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('editor');
  const [saving, setSaving] = React.useState(false);

  /* Refresh team on mount */
  React.useEffect(() => {
    if (app.refreshTeam) app.refreshTeam();
  }, []);

  async function sendInvite() {
    if (!/.+@.+\..+/.test(email)) return;
    setSaving(true);
    try {
      await API.inviteMember(email.trim(), role);
      app.update((s) => { s.team.push({ name: '', email: email.trim(), role, status: 'invited' }); });
      app.toast('Invite sent to ' + email.trim());
      setInviting(false); setEmail('');
    } catch (e) {
      app.toast('Error: ' + e.message);
    } finally {
      setSaving(false);
    }
  }

  async function changeRole(member, newRole) {
    try {
      await API.updateMemberRole(member.id, newRole);
      app.update((s) => { const m = s.team.find((x) => x.email === member.email); if (m) m.role = newRole; });
      app.toast(member.email + ' is now ' + (newRole === 'editor' ? 'an editor' : 'a viewer'));
    } catch (e) {
      app.toast('Error: ' + e.message);
    }
  }

  async function removeMember(member) {
    try {
      await API.removeMember(member.id);
      app.update((s) => { s.team = s.team.filter((x) => x.email !== member.email); });
      app.toast(member.email + ' removed');
    } catch (e) {
      app.toast('Error: ' + e.message);
    }
  }

  return (
    <div data-screen-label="SET2 Team">
      <div className="row-between" style={{ marginBottom: 14 }}>
        <p className="mutetext" style={{ margin: 0, fontSize: 13 }}>
          Owners run billing and the team. Editors create links and change destinations. Viewers read the numbers.
        </p>
        <button className="abtn abtn-primary abtn-sm" onClick={() => setInviting(true)}><Icon name="plus" size={14} />Invite</button>
      </div>
      <table className="atable">
        <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {team.map((m, i) => (
            <tr key={m.email} style={{ cursor: 'default' }}>
              <td style={{ fontWeight: 600 }}>{m.name || <span className="mutetext">Invited</span>}</td>
              <td className="tdest" style={{ maxWidth: 'none' }}>{m.email}</td>
              <td>
                {m.role === 'owner' ? <span style={{ fontWeight: 600 }}>Owner</span> : (
                  <select className="ainput" style={{ width: 'auto', padding: '4px 8px', fontSize: 12.5 }} value={m.role}
                    onChange={(e) => changeRole(m, e.target.value)}>
                    <option value="editor">Editor</option>
                    <option value="viewer">Viewer</option>
                  </select>
                )}
              </td>
              <td><span className="mutetext" style={{ fontSize: 12.5 }}>{m.status === 'invited' ? 'Invite sent' : 'Active'}</span></td>
              <td style={{ textAlign: 'right' }}>
                {m.role !== 'owner' ? (
                  <button className="abtn abtn-quiet abtn-sm" style={{ color: 'var(--danger)' }} onClick={() => removeMember(m)}>Remove</button>
                ) : null}
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {inviting ? (
        <Modal title="Invite someone" onClose={() => setInviting(false)}>
          <p>They get an email with a link to join {app.state.vendor.name}.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 18 }}>
            <input className="ainput" placeholder="name@business.com.au" value={email} autoFocus onChange={(e) => setEmail(e.target.value)} />
            <Seg value={role} options={[{ value: 'editor', label: 'Editor' }, { value: 'viewer', label: 'Viewer' }]} onChange={setRole} />
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="abtn abtn-quiet" onClick={() => setInviting(false)}>Cancel</button>
            <button className="abtn abtn-primary" disabled={!/.+@.+\..+/.test(email) || saving} onClick={sendInvite}>
              {saving ? 'Sending…' : 'Send invite'}
            </button>
          </div>
        </Modal>
      ) : null}
    </div>
  );
}

Object.assign(window, { CardModal, Billing, Settings });
