// Merchavio — Settings detail screens: Domains + Team access.
// Drill-down screens opened from SettingsScreen (screens-extra2.jsx). Both are
// full Frames with onBack, so they work on desktop (back button) and mobile
// (the ☰ becomes a ‹ chevron). Exports (window): DomainsScreen, TeamScreen.

// ── shared: a copyable DNS record row ─────────────────────────
function CopyRow({ type, host, value }) {
  const [copied, setCopied] = React.useState(false);
  const copy = () => {
    try { navigator.clipboard && navigator.clipboard.writeText(value); } catch (e) {}
    setCopied(true); setTimeout(() => setCopied(false), 1300);
  };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '64px 1fr auto', alignItems: 'center', gap: 12, padding: '11px 14px', borderTop: `1px solid ${T.hair}` }}>
      <span style={{ fontFamily: T.mono, fontSize: 10.5, fontWeight: 600, color: T.muted, letterSpacing: 0.5 }}>{type}</span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: T.mono, fontSize: 9.5, color: T.dim, textTransform: 'uppercase', letterSpacing: 0.8 }}>Host {host}</div>
        <div style={{ fontFamily: T.mono, fontSize: 12.5, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
      </div>
      <button onClick={copy} className="dg-tap" title="Copy value" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 28, padding: '0 10px', borderRadius: 8, border: `1px solid ${copied ? T.good : T.line}`, background: copied ? T.goodBg : T.surface, color: copied ? T.good : T.text, cursor: 'pointer', fontFamily: T.sans, fontSize: 12, fontWeight: 600 }}>
        <Icon name={copied ? 'check' : 'copy'} size={13} color={copied ? T.good : T.muted} /> {copied ? 'Copied' : 'Copy'}
      </button>
    </div>
  );
}

function DomainsScreen({ onBack }) {
  // Real store state: slug + custom domain live in the settings singleton.
  const [settings, setSettings] = dgStore.useSingleton('settings');
  const u = dgStore.user() || {};
  const slug = settings.storefront_slug || u.store_slug || '';
  const freeAddress = (slug || 'your-store') + '.merchavio.com';
  const primary = (settings.custom_domain || '').trim();
  const [input, setInput] = React.useState('');
  const [pending, setPending] = React.useState(null);   // the domain being connected
  const [checking, setChecking] = React.useState(false);
  const verified = !!settings.custom_domain_verified;

  const connect = () => {
    const d = input.trim().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    if (!d) return;
    setPending(d); setChecking(false);
  };
  const verify = () => {
    setChecking(true);
    setTimeout(() => {
      setChecking(false);
      setSettings({ custom_domain: pending, custom_domain_verified: true });
      setPending(null); setInput('');
      window.dgToast && window.dgToast(`“${pending}” connected`, 'good');
    }, 1400);
  };
  const removeDomain = async () => {
    if (window.dgConfirm && !(await dgConfirm(`Remove “${primary}”? Your store stays reachable at ${freeAddress}.`, { confirmLabel: 'Remove', danger: true }))) return;
    setSettings({ custom_domain: '', custom_domain_verified: false });
    window.dgToast && window.dgToast('Domain removed');
  };
  const editSlug = async () => {
    if (!window.dgPrompt) return;
    const v = await dgPrompt('Store address', { label: 'Store-URL (slug)', value: slug, placeholder: 'your-store' });
    if (v == null) return;
    const s = String(v).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
    if (!s) return window.dgToast('Enter a slug first', 'bad');
    const res = await dgStore.saveProfile({ store_slug: s, store_name: settings.trading_name || undefined });
    if (res && res.ok) { setSettings({ storefront_slug: s }); window.dgToast(`Store address is now ${s}.merchavio.com`, 'good'); }
    else window.dgToast((res && res.error) || 'Could not save slug', 'bad');
  };

  return (
    <Frame active="settings" onBack={onBack} breadcrumbs={['Settings', 'Domains']} title="Domains" scrollable
      actions={<Btn kind="primary" size="md" icon="plus" onClick={() => { const el = document.getElementById('mv-domain-input'); el && el.focus(); }}>Connect domain</Btn>}>
      <div style={{ padding: '20px 24px 44px', maxWidth: 720, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 20 }}>

        {/* Primary connected domain */}
        {primary && (
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.muted, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8, paddingLeft: 2 }}>Primary domain</div>
          <Card p={0}>
            <div style={{ padding: '16px 18px', display: 'flex', alignItems: 'flex-start', gap: 13 }}>
              <div style={{ width: 42, height: 42, borderRadius: T.r3, background: `linear-gradient(140deg, ${T.accent}, ${T.accentDeep})`, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 42px', boxShadow: T.sh1 }}>
                <Icon name="globe" size={21} color="#fff" strokeWidth={1.7} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <HS gap={8} style={{ flexWrap: 'wrap' }}>
                  <span style={{ fontFamily: T.sans, fontSize: 17, fontWeight: 700, color: T.ink, letterSpacing: -0.3 }}>{primary}</span>
                  <Pill color="ink">Primary</Pill>
                </HS>
                <HS gap={7} style={{ marginTop: 8, flexWrap: 'wrap' }}>
                  {verified ? <Pill color="good"><Dot color={T.good} size={6} /> DNS verified</Pill> : <Pill color="warn"><Dot color={T.warn} size={6} /> DNS pending</Pill>}
                  {verified && <Pill color="neutral"><Icon name="lock" size={11} color={T.muted} /> SSL active</Pill>}
                </HS>
              </div>
            </div>
            <HS gap={8} style={{ padding: '11px 14px', borderTop: `1px solid ${T.hair}`, background: T.surface2, borderRadius: `0 0 ${T.r3}px ${T.r3}px` }}>
              <Btn size="sm" icon="settings" onClick={() => { setPending(primary); const el = document.getElementById('mv-domain-input'); el && el.scrollIntoView({ behavior: 'smooth', block: 'center' }); }}>Manage DNS</Btn>
              <Btn size="sm" icon="external" onClick={() => window.open('https://' + primary, '_blank')}>Visit</Btn>
              <div style={{ flex: 1 }} />
              <Btn size="sm" icon="trash" style={{ color: T.bad }} onClick={removeDomain}>Remove</Btn>
            </HS>
          </Card>
        </div>
        )}

        {/* Free Merchavio subdomain */}
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.muted, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8, paddingLeft: 2 }}>Merchavio address</div>
          <Card style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 34, height: 34, borderRadius: T.r2, background: T.surface2, border: `1px solid ${T.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 34px' }}>
              <Icon name="link" size={16} color={T.muted} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: T.sans, fontSize: 14, fontWeight: 600, color: T.ink }}>{freeAddress}</div>
              <div style={{ fontFamily: T.sans, fontSize: 12, color: T.muted, marginTop: 1 }}>Free address · always available{primary ? ', redirects to your primary domain' : ''}</div>
            </div>
            <Btn size="sm" icon="edit" onClick={editSlug}>Edit</Btn>
            <Pill color="neutral">Default</Pill>
          </Card>
        </div>

        {/* Connect a domain you own */}
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.muted, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8, paddingLeft: 2 }}>Add a domain</div>
          <Card style={{ padding: 16 }}>
            <div style={{ fontFamily: T.sans, fontSize: 14.5, fontWeight: 600, color: T.ink }}>Connect a domain you own</div>
            <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, marginTop: 3, lineHeight: 1.5 }}>Point an existing domain from any registrar (GoDaddy, Namecheap, IONOS…) to your store.</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 13, flexWrap: 'wrap' }}>
              <div style={{ flex: '1 1 220px', minWidth: 0 }}>
                <Input full id="mv-domain-input" leading={<span style={{ fontFamily: T.mono, fontSize: 12, color: T.dim }}>https://</span>} placeholder="yourdomain.com" value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') connect(); }} />
              </div>
              <Btn kind="primary" size="lg" icon="arrowright" onClick={connect} style={{ flex: '0 0 auto' }}>Connect</Btn>
            </div>

            {pending && (
              <div style={{ marginTop: 16, border: `1px solid ${T.line}`, borderRadius: T.r3, overflow: 'hidden' }}>
                <div style={{ padding: '11px 14px', background: T.surface2, borderBottom: `1px solid ${T.line}` }}>
                  <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.text, lineHeight: 1.5 }}>Add these two records at your registrar to verify <b style={{ color: T.ink }}>{pending}</b>:</div>
                </div>
                <CopyRow type="A" host="@" value="76.76.21.21" />
                <CopyRow type="CNAME" host="www" value="cname.merchavio.app" />
                <HS gap={9} style={{ padding: '12px 14px', borderTop: `1px solid ${T.hair}` }}>
                  <span style={{ position: 'relative', width: 8, height: 8, flex: '0 0 8px' }}>
                    <span style={{ position: 'absolute', inset: 0, borderRadius: '50%', background: T.warn, opacity: checking ? 1 : 0.55, animation: checking ? 'plinthPulseRing 1.2s ease-out infinite' : 'none' }} />
                  </span>
                  <span style={{ flex: 1, fontFamily: T.sans, fontSize: 12.5, color: T.muted }}>{checking ? 'Checking DNS records…' : 'Waiting for DNS — add the records above, then verify.'}</span>
                  <Btn size="sm" icon={checking ? 'refresh' : 'check'} onClick={verify}>{checking ? 'Checking…' : 'Verify now'}</Btn>
                </HS>
              </div>
            )}
            <div style={{ fontFamily: T.mono, fontSize: 10, color: T.dim, marginTop: 11, letterSpacing: 0.3 }}>DNS changes can take up to 48h to propagate. SSL is issued automatically once verified.</div>
          </Card>
        </div>

      </div>
    </Frame>
  );
}

Object.assign(window, { DomainsScreen, CopyRow });

// ── Team access ───────────────────────────────────────────────
const TEAM_ROLES = {
  Owner: { icon: 'shield', color: T.ink, desc: 'Full access, including billing, team management and deleting the store.' },
  Admin: { icon: 'key', color: T.plum, desc: 'Everything except billing and deleting the store.' },
  Staff: { icon: 'user', color: T.accent, desc: 'Only the areas you assign below.' },
};
const STAFF_AREAS = ['Products', 'Orders & customers', 'Finance & payouts', 'Community & courses', 'Marketing', 'Analytics'];

function RoleSelect({ value, onChange }) {
  return (
    <div style={{ position: 'relative' }}>
      <select value={value} onChange={e => onChange(e.target.value)} style={{ appearance: 'none', WebkitAppearance: 'none', height: 30, padding: '0 26px 0 10px', borderRadius: 8, border: `1px solid ${T.line}`, background: T.surface, color: T.text, fontFamily: T.sans, fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>
        <option>Admin</option>
        <option>Staff</option>
      </select>
      <span style={{ position: 'absolute', right: 9, top: 8, pointerEvents: 'none' }}><Icon name="chevdown" size={13} color={T.muted} /></span>
    </div>
  );
}

function InviteSheet({ onClose, onInvite }) {
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('Staff');
  const [areas, setAreas] = React.useState(() => ({ 'Products': true, 'Orders & customers': true, 'Community & courses': true }));
  const toggle = (a) => setAreas(s => ({ ...s, [a]: !s[a] }));
  const send = () => {
    if (!email.trim()) { const el = document.getElementById('mv-invite-email'); el && el.focus(); return; }
    onInvite({ email: email.trim(), role });
  };
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 130, background: 'rgba(34,29,22,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, animation: 'dgfade .18s ease' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 480, maxWidth: '100%', maxHeight: '90%', overflow: 'auto', background: T.surface, borderRadius: T.r4, border: `1px solid ${T.line}`, boxShadow: T.sh4 }}>
        <HS justify="space-between" style={{ padding: '15px 18px', borderBottom: `1px solid ${T.line}` }}>
          <div style={{ fontFamily: T.sans, fontSize: 15.5, fontWeight: 700, color: T.ink }}>Invite a team member</div>
          <button onClick={onClose} className="dg-tap" style={{ width: 30, height: 30, borderRadius: 8, border: `1px solid ${T.line}`, background: T.surface, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><Icon name="x" size={15} color={T.muted} /></button>
        </HS>
        <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Input full label="Email address" id="mv-invite-email" leading={<Icon name="mail" size={14} color={T.dim} />} placeholder="name@company.com" value={email} onChange={e => setEmail(e.target.value)} />
          <div>
            <FieldLabel>Role</FieldLabel>
            <Seg options={['Admin', 'Staff']} value={role} onChange={setRole} />
            <div style={{ fontFamily: T.sans, fontSize: 12, color: T.muted, marginTop: 7, lineHeight: 1.5 }}>{TEAM_ROLES[role].desc}</div>
          </div>
          {role === 'Staff' && (
            <div>
              <FieldLabel>Access to</FieldLabel>
              <div style={{ border: `1px solid ${T.line}`, borderRadius: T.r3, overflow: 'hidden' }}>
                {STAFF_AREAS.map((a, i) => (
                  <HS key={a} justify="space-between" style={{ padding: '11px 13px', borderTop: i ? `1px solid ${T.hair}` : 'none' }}>
                    <span style={{ fontFamily: T.sans, fontSize: 13, color: T.text }}>{a}</span>
                    <Toggle on={!!areas[a]} onChange={() => toggle(a)} />
                  </HS>
                ))}
              </div>
            </div>
          )}
        </div>
        <HS gap={9} justify="flex-end" style={{ padding: '13px 18px', borderTop: `1px solid ${T.line}`, background: T.surface2, borderRadius: `0 0 ${T.r4}px ${T.r4}px` }}>
          <Btn onClick={onClose}>Cancel</Btn>
          <Btn kind="primary" icon="mail" onClick={send}>Send invite</Btn>
        </HS>
      </div>
    </div>
  );
}

function TeamScreen({ onBack }) {
  // Real data: the owner comes from the signed-in account; additional members
  // are persisted in the `team_members` collection (synced like any other).
  const u = dgStore.user() || {};
  const [settings] = dgStore.useSingleton('settings');
  const [extra, tm] = dgStore.useCollection('team_members');
  const owner = { id: '_owner', name: u.name || u.full_name || 'You', email: u.email || '', role: 'Owner', last: 'Active now', you: true };
  const members = [owner, ...extra];
  const [invite, setInvite] = React.useState(false);
  const setRole = (id, role) => tm.update(id, { role });
  const remove = async (id) => {
    const m = extra.find(x => x.id === id);
    if (m && !m.pending && window.dgConfirm && !(await dgConfirm(`Remove ${m.name} from the team?`, { confirmLabel: 'Remove', danger: true }))) return;
    tm.remove(id);
  };
  const addInvite = ({ email, role }) => {
    tm.add({ name: email.split('@')[0].replace(/[._-]/g, ' ').replace(/\b\w/g, c => c.toUpperCase()), email, role, pending: true });
    setInvite(false);
    window.dgToast && window.dgToast(`Invite for ${email} created`, 'good');
  };
  const resend = (m) => {
    try { navigator.clipboard && navigator.clipboard.writeText(`https://merchavio.com/#/signup?invite=${encodeURIComponent(m.email)}`); } catch (e) {}
    window.dgToast && window.dgToast('Invite link copied — send it to your teammate', 'good');
  };
  const plan = settings.plan || (u.plan || 'Starter');
  const seats = ({ Starter: 2, Growth: 5, Scale: 15 })[plan] || 5;
  const used = members.length;

  return (
    <Frame active="settings" onBack={onBack} breadcrumbs={['Settings', 'Team']} title="Team access" scrollable
      actions={<Btn kind="primary" size="md" icon="plus" onClick={() => setInvite(true)}>Invite member</Btn>}>
      <div style={{ padding: '20px 24px 44px', maxWidth: 720, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 20 }}>

        {/* Seats */}
        <Card style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 13 }}>
          <div style={{ width: 40, height: 40, borderRadius: T.r3, background: T.accentBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 40px' }}><Icon name="users" size={20} color={T.accent} strokeWidth={1.7} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: T.sans, fontSize: 14, fontWeight: 600, color: T.ink }}>{used} of {seats} seats used</div>
            <div style={{ fontFamily: T.sans, fontSize: 12, color: T.muted, marginTop: 1 }}>Growth plan · invite up to {seats} teammates</div>
          </div>
          <div style={{ width: 108, height: 6, borderRadius: 99, background: T.surface2, overflow: 'hidden', flex: '0 0 108px' }}>
            <div style={{ width: `${Math.min(100, used / seats * 100)}%`, height: '100%', borderRadius: 99, background: `linear-gradient(90deg, ${T.accent}, ${T.accentDeep})` }} />
          </div>
        </Card>

        {/* Members */}
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.muted, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8, paddingLeft: 2 }}>Members</div>
          <Card p={0}>
            {members.map((m, i) => (
              <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', borderTop: i ? `1px solid ${T.hair}` : 'none' }}>
                <Avatar name={m.name} size={38} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <HS gap={7}>
                    <span style={{ fontFamily: T.sans, fontSize: 14, fontWeight: 600, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.name}</span>
                    {m.you && <Pill color="neutral">You</Pill>}
                    {m.pending && <Pill color="warn">Pending</Pill>}
                  </HS>
                  <div style={{ fontFamily: T.sans, fontSize: 12, color: T.muted, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.email}{!m.pending && <span style={{ color: T.dim }}> · {m.last}</span>}</div>
                </div>
                {m.role === 'Owner'
                  ? <Pill color="ink"><Icon name="shield" size={11} color="#fff" /> Owner</Pill>
                  : <RoleSelect value={m.role} onChange={r => setRole(m.id, r)} />}
                {m.pending
                  ? <HS gap={4}><Btn size="sm" onClick={() => resend(m)}>Resend</Btn><button onClick={() => remove(m.id)} className="dg-tap" title="Cancel invite" style={{ width: 30, height: 30, borderRadius: 8, border: `1px solid ${T.line}`, background: T.surface, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><Icon name="x" size={14} color={T.muted} /></button></HS>
                  : !m.you && <button onClick={() => remove(m.id)} className="dg-tap" title="Remove member" style={{ width: 30, height: 30, borderRadius: 8, border: `1px solid ${T.line}`, background: T.surface, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flex: '0 0 30px' }}><Icon name="trash" size={14} color={T.muted} /></button>}
              </div>
            ))}
          </Card>
        </div>

        {/* Roles explainer */}
        <div>
          <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.muted, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8, paddingLeft: 2 }}>Roles &amp; permissions</div>
          <Card p={0}>
            {Object.keys(TEAM_ROLES).map((r, i) => (
              <HS key={r} gap={12} align="flex-start" style={{ padding: '13px 16px', borderTop: i ? `1px solid ${T.hair}` : 'none' }}>
                <div style={{ width: 32, height: 32, borderRadius: T.r2, background: T.surface2, border: `1px solid ${T.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 32px' }}><Icon name={TEAM_ROLES[r].icon} size={16} color={TEAM_ROLES[r].color} /></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: T.sans, fontSize: 13.5, fontWeight: 600, color: T.ink }}>{r}</div>
                  <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, marginTop: 2, lineHeight: 1.5 }}>{TEAM_ROLES[r].desc}</div>
                </div>
              </HS>
            ))}
          </Card>
        </div>

      </div>
      {invite && <InviteSheet onClose={() => setInvite(false)} onInvite={addInvite} />}
    </Frame>
  );
}

Object.assign(window, { TeamScreen, InviteSheet });

