/* A3 — Settings & retention. Photos pending deletion, the retention rule, team (admin only). */
const Sset = window.SparkleClassicDesignSystem_7a1470;

function daysLeft(ageHours) { return Math.max(0, Math.ceil((7 * 24 - ageHours) / 24)); }

function RetentionPanel({ orders }) {
  const { Card, Button, Icon, Badge, Sparkle } = Sset;
  const initial = orders.filter((o) => o.photo && o.photo.state === 'present')
    .map((o) => ({ id: o.id, pet: o.petName, ageHours: o.photo.ageHours }));
  const [pending, setPending] = React.useState(initial);
  const overdue = pending.filter((p) => p.ageHours >= 7 * 24).length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card surface={overdue ? 'card' : 'cream'} padding="md">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 36, height: 36, flex: '0 0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', background: overdue ? 'var(--warning-tint)' : 'var(--mint)', color: 'var(--plum-ink)', boxShadow: 'var(--ofx-edges)' }}><Icon name={overdue ? 'alert' : 'check'} /></span>
          <div>
            <strong style={{ fontSize: 15, color: 'var(--plum-ink)' }}>{overdue ? `${overdue} photo(s) overdue` : 'Nothing overdue'}</strong>
            <div className="spk-muted" style={{ fontSize: 13.5 }}>
              {overdue ? 'Delete these now to keep the promise.' : <span>Every photo is on track to auto-delete on time. <Sparkle size={12} /></span>}
            </div>
          </div>
        </div>
      </Card>

      <Card surface="card" padding="lg">
        <p className="spk-eyebrow" style={{ marginBottom: 4 }}>HOW LONG WE KEEP PHOTOS</p>
        <p style={{ margin: 0, fontSize: 15, color: 'var(--plum-ink)', lineHeight: 1.6 }}>{RETENTION_RULE}</p>
      </Card>

      <Card surface="card" padding="lg">
        <p className="spk-eyebrow" style={{ marginBottom: 12 }}>PHOTOS PENDING DELETION</p>
        {pending.length === 0 ? (
          <p className="spk-muted" style={{ margin: 0, fontSize: 14 }}>No photos are being stored right now.</p>
        ) : (
          <div style={{ display: 'grid', gap: 10 }}>
            {pending.map((p) => {
              const d = daysLeft(p.ageHours);
              return (
                <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', boxShadow: 'var(--ofx-edges)', background: 'var(--white)', flexWrap: 'wrap' }}>
                  <div style={{ flex: 1, minWidth: 140 }}>
                    <strong style={{ fontSize: 14, color: 'var(--plum-ink)' }}>{p.pet}</strong>
                    <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 8, color: 'var(--plum-accent)', marginLeft: 8 }}>{p.id}</span>
                    <div className="spk-muted" style={{ fontSize: 12.5 }}>Uploaded {p.ageHours}h ago · auto-deletes in {d} day{d === 1 ? '' : 's'}</div>
                  </div>
                  {d <= 1 && <Badge tone="warning" dot>Soon</Badge>}
                  <Button variant="ghost" size="sm" leftIcon={<Icon name="trash" />} onClick={() => setPending((list) => list.filter((x) => x.id !== p.id))}>Delete now</Button>
                </div>
              );
            })}
          </div>
        )}
      </Card>
    </div>
  );
}

function TeamPanel({ role }) {
  const { Card, Button, Icon, Badge, Avatar, Dialog, Input, Select } = Sset;
  const [team, setTeam] = React.useState(TEAM);
  const [add, setAdd] = React.useState(false);
  const [note, setNote] = React.useState(null);
  const flash = (m) => { setNote(m); setTimeout(() => setNote(null), 2400); };

  if (!can(role, 'manageTeam')) {
    return (
      <Card surface="card" padding="lg">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--cream)', color: 'var(--plum-ink)', boxShadow: 'var(--ofx-edges)' }}><Icon name="lock" /></span>
          <div><strong style={{ fontSize: 15, color: 'var(--plum-ink)' }}>Team settings are admin-only</strong><div className="spk-muted" style={{ fontSize: 13.5 }}>Ask Ada (owner) to add or change accounts.</div></div>
        </div>
      </Card>
    );
  }

  return (
    <Card surface="card" padding="lg">
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, gap: 10, flexWrap: 'wrap' }}>
        <p className="spk-eyebrow" style={{ margin: 0 }}>TEAM</p>
        <Button variant="secondary" size="sm" leftIcon={<Icon name="plus" />} onClick={() => setAdd(true)}>Add member</Button>
      </div>
      <div style={{ display: 'grid', gap: 10 }}>
        {team.map((m) => (
          <div key={m.email} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', boxShadow: 'var(--ofx-edges)', background: 'var(--white)', flexWrap: 'wrap' }}>
            <Avatar name={m.name} size="sm" />
            <div style={{ flex: 1, minWidth: 150 }}>
              <strong style={{ fontSize: 14, color: 'var(--plum-ink)' }}>{m.name}{m.you ? ' (you)' : ''}</strong>
              <div className="spk-muted" style={{ fontSize: 12.5, wordBreak: 'break-all' }}>{m.email}</div>
            </div>
            <Badge tone={m.role === 'admin' ? 'success' : 'neutral'} dot>{ROLES[m.role].label}</Badge>
            <Button variant="ghost" size="sm" onClick={() => flash(`Reset link sent to ${m.email}.`)}>Reset password</Button>
            {!m.you && <Button variant="ghost" size="sm" leftIcon={<Icon name="trash" />} onClick={() => setTeam((t) => t.filter((x) => x.email !== m.email))}>Remove</Button>}
          </div>
        ))}
      </div>
      {note && <p style={{ margin: '12px 0 0', fontSize: 13, fontWeight: 700, color: 'var(--success)', display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={15} /> {note}</p>}

      <Dialog open={add} onClose={() => setAdd(false)} title="Add a team member"
        footer={<React.Fragment>
          <Button variant="ghost" onClick={() => setAdd(false)}>Cancel</Button>
          <Button variant="primary" onClick={() => { setAdd(false); flash('Invite emailed.'); }}>Send invite</Button>
        </React.Fragment>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, textAlign: 'left' }}>
          <Input label="Name" placeholder="e.g. Sky Rivera" />
          <Input label="Email" type="email" placeholder="name@sparkleclassic.com" leftIcon={<Icon name="mail" />} />
          <Select label="Role" options={[{ value: 'crp', label: 'Support / CRP' }, { value: 'admin', label: 'Admin' }]} />
        </div>
      </Dialog>
    </Card>
  );
}

// Admin-only: toggle the support (crp) role's elevated permissions. Persisted in
// the shared DB; every use of an elevated permission is logged on the order.
function PermsPanel({ crpPerms, onCrpPerms }) {
  const { Card } = Sset;
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const set = async (k, val) => {
    setSaving(true); setErr(null);
    const next = { ...(crpPerms || {}), [k]: val };
    try {
      const r = await apiFetch('/api/orders', { method: 'POST', body: JSON.stringify({ op: 'crp-perms', perms: next }) });
      onCrpPerms(r.crpPerms || next);
    } catch (e) { setErr(e.message || 'Could not save'); } finally { setSaving(false); }
  };
  const Row = ({ k, label, desc }) => {
    const on = !!(crpPerms && crpPerms[k]);
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'space-between', padding: '12px 0', borderBottom: '1px solid var(--border-soft)' }}>
        <div><strong style={{ fontSize: 14.5, color: 'var(--plum-ink)' }}>{label}</strong><div className="spk-muted" style={{ fontSize: 13 }}>{desc}</div></div>
        <button onClick={() => set(k, !on)} disabled={saving} aria-pressed={on} style={{
          flexShrink: 0, fontFamily: 'var(--font-body)', fontWeight: 800, fontSize: 12.5, cursor: saving ? 'wait' : 'pointer', padding: '7px 14px', border: 0,
          boxShadow: 'var(--ofx-edges)', background: on ? 'var(--success)' : 'var(--cream-surface)', color: on ? 'var(--cream)' : 'var(--plum-ink)',
        }}>{on ? 'ON' : 'OFF'}</button>
      </div>
    );
  };
  return (
    <Card surface="card" padding="md" shadow="block">
      <h3 className="spk-h4" style={{ fontSize: 17, margin: '0 0 2px' }}>Support permissions</h3>
      <p className="spk-muted" style={{ fontSize: 13.5, margin: '0 0 8px' }}>Grant the Support role abilities normally reserved for the owner. Every use is logged on the order’s activity, with who did it.</p>
      {err && <p style={{ color: 'var(--danger)', fontSize: 13, fontWeight: 700 }}>{err}</p>}
      <Row k="confirmRefund" label="Support can confirm refunds" desc="Lets a Support login issue a Stripe refund (otherwise they can only request one)." />
    </Card>
  );
}

function SettingsScreen({ orders, role, crpPerms, onCrpPerms }) {
  const { Tabs, Icon } = Sset;
  const [tab, setTab] = React.useState('retention');
  const items = [{ id: 'retention', label: 'Privacy & retention' }, { id: 'team', label: 'Team' }];
  if (role === 'admin') items.push({ id: 'perms', label: 'Permissions' });
  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <h1 className="spk-h2" style={{ fontSize: 26, margin: '0 0 4px' }}>Settings</h1>
        <p className="spk-muted" style={{ fontSize: 14, margin: 0 }}>Operate the privacy promise and manage who can do what.</p>
      </div>
      <div style={{ marginBottom: 16 }}>
        <Tabs value={tab} onChange={setTab} items={items} />
      </div>
      {tab === 'retention' ? <RetentionPanel orders={orders} /> : tab === 'perms' ? <PermsPanel crpPerms={crpPerms} onCrpPerms={onCrpPerms} /> : <TeamPanel role={role} />}
      <p className="spk-muted" style={{ fontSize: 13, marginTop: 18, display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="external-link" size={14} aria-hidden="true" /> Anything not here lives in <a href="#stripe">Stripe</a> — payments, payouts, and disputes.
      </p>
    </div>
  );
}

Object.assign(window, { SettingsScreen });
