// Share / co-parent invite screen — real invites backed by Supabase.
// Owners can email-invite co-parents/helpers/viewers, see pending invites with
// shareable join links, and see who's currently in the household.

const ROLE_OPTIONS = [
  { id: 'parent', name: 'Co-parent', desc: 'Full access. Can edit tasks, mark things done, manage rewards.' },
  { id: 'helper', name: 'Helper (grandparent, carer)', desc: 'Can mark tasks done. Cannot change task points or rewards.' },
  { id: 'viewer', name: 'Viewer', desc: 'Read-only. Sees activity but cannot mark anything.' },
];

function joinLinkFor(token) {
  // Hash-route based link so it works on the same single-page app.
  const base = window.location.origin + window.location.pathname.replace(/\/$/, '');
  return `${base}/#/join/${token}`;
}

function ShareScreen() {
  const s = window.useStore();
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('parent');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [flash, setFlash] = React.useState(null);

  const householdName = s.household?.name || 'Your Family';
  const isOwner = !!(s.household && s.user && s.household.owner_id === s.user.id);

  // Show successful-redeem flash once, then clear it from the store.
  React.useEffect(() => {
    if (s.inviteRedeemed) {
      setFlash(`You joined ${s.inviteRedeemed.household_name || 'a family'} as ${labelForRole(s.inviteRedeemed.role)}.`);
      s.clearInviteFlash?.();
    } else if (s.inviteError) {
      setErr(s.inviteError);
      s.clearInviteFlash?.();
    }
  }, [s.inviteRedeemed, s.inviteError]); // eslint-disable-line

  const pending = (s.invitations || []).filter(i => i.status === 'pending');
  const past = (s.invitations || []).filter(i => i.status !== 'pending');

  const submit = async (e) => {
    e?.preventDefault?.();
    setErr(null);
    const v = email.trim();
    if (!v) { setErr('Email is required.'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) { setErr("That doesn't look like a valid email."); return; }
    setBusy(true);
    try {
      const { row, delivery } = await s.createInvitation(v, role);
      setEmail('');
      if (delivery?.sent) {
        setFlash(`✉️  Invite emailed to ${row.invited_email}. Tell them to check their inbox (and spam folder, just in case).`);
      } else {
        const why = delivery?.reason || 'email delivery is not set up yet';
        setFlash(`Invite created for ${row.invited_email}. Email wasn't sent — ${why}. Copy the link below to share it manually.`);
      }
    } catch (e2) {
      const m = e2?.message || 'Could not create invite.';
      setErr(/duplicate key|unique/i.test(m)
        ? `${v} already has a pending invite. Revoke it first or use a different email.`
        : m);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="screen">
      <header style={{ marginBottom: 32 }}>
        <window.Eyebrow>Settings · Family</window.Eyebrow>
        <h1 className="h-display h1" style={{ marginTop: 6 }}>Share with your family.</h1>
        <p className="lede" style={{ marginTop: 10 }}>
          Invite a co-parent, helper, or viewer. They sign in with Google — no passwords to share.
        </p>
        {flash && (
          <div style={flashStyle('ok')}>
            <span>✓</span><span>{flash}</span>
            <button className="x-btn" onClick={() => setFlash(null)}>×</button>
          </div>
        )}
        {err && (
          <div style={flashStyle('err')}>
            <span>!</span><span>{err}</span>
            <button className="x-btn" onClick={() => setErr(null)}>×</button>
          </div>
        )}
      </header>

      <div className="share-grid">
        {/* LEFT — invite form + pending invites */}
        <div>
          <div className="card">
            <h3 className="h-display h3" style={{ marginBottom: 4 }}>Invite by email</h3>
            <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginBottom: 20 }}>
              We create a unique join link they can use to sign in with Google and join {householdName}.
            </div>

            {!isOwner && (
              <div style={{
                padding: '12px 14px', borderRadius: 12, background: 'var(--cream-deep)',
                color: 'var(--ink)', fontSize: 13, marginBottom: 18,
              }}>
                Only the household owner can send invites.
              </div>
            )}

            <form onSubmit={submit}>
              <div className="field" style={{ marginBottom: 16 }}>
                <label>Email</label>
                <input type="email" placeholder="rohan@example.com"
                  value={email} onChange={(e) => setEmail(e.target.value)}
                  disabled={!isOwner || busy} />
              </div>

              <div className="field" style={{ marginBottom: 24 }}>
                <label>Their role</label>
                <div style={{ display: 'grid', gap: 8 }}>
                  {ROLE_OPTIONS.map(r => (
                    <button type="button" key={r.id} onClick={() => setRole(r.id)}
                      disabled={!isOwner}
                      style={{
                        textAlign: 'left', display: 'flex', alignItems: 'flex-start', gap: 12,
                        padding: '14px 16px', borderRadius: 14,
                        background: 'var(--paper)',
                        border: role === r.id ? '2px solid var(--ink)' : '2px solid var(--rule-strong)',
                        cursor: isOwner ? 'pointer' : 'not-allowed',
                        opacity: isOwner ? 1 : 0.6,
                      }}>
                      <div style={{
                        width: 18, height: 18, borderRadius: 50, marginTop: 2,
                        border: '2px solid var(--ink)',
                        background: role === r.id ? 'var(--ink)' : 'transparent',
                        boxShadow: role === r.id ? 'inset 0 0 0 3px var(--paper)' : undefined,
                        flex: 'none',
                      }} />
                      <div>
                        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15 }}>{r.name}</div>
                        <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 2 }}>{r.desc}</div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              <button type="submit" className="btn btn-primary"
                disabled={!isOwner || busy}
                style={{ width: '100%', padding: '14px 22px', fontSize: 16,
                         opacity: (!isOwner || busy) ? 0.6 : 1,
                         cursor: (!isOwner || busy) ? 'not-allowed' : 'pointer' }}>
                {busy ? 'Creating invite…' : 'Create invite'}
              </button>
            </form>
          </div>

          {pending.length > 0 && (
            <div className="card" style={{ marginTop: 16 }}>
              <h3 className="h-display h3" style={{ marginBottom: 4 }}>Pending invites</h3>
              <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginBottom: 18 }}>
                Copy the link and send it via WhatsApp, email, iMessage — anywhere.
              </div>
              <div style={{ display: 'grid', gap: 12 }}>
                {pending.map(inv => <PendingRow key={inv.id} inv={inv}
                  canManage={isOwner}
                  onRevoke={() => s.revokeInvitation(inv.id)} />)}
              </div>
            </div>
          )}

          {past.length > 0 && (
            <details className="card" style={{ marginTop: 16 }}>
              <summary style={{ cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15 }}>
                Past invites ({past.length})
              </summary>
              <div style={{ display: 'grid', gap: 10, marginTop: 14 }}>
                {past.map(inv => (
                  <div key={inv.id} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
                    <span style={{ flex: 1, wordBreak: 'break-all' }}>{inv.invited_email}</span>
                    <span className="chip" style={{
                      background: inv.status === 'accepted' ? 'var(--mint-soft)' : 'var(--cream-deep)',
                      color: inv.status === 'accepted' ? '#156142' : 'var(--ink-soft)',
                    }}>{inv.status}</span>
                    <span style={{ color: 'var(--ink-faint)' }}>{labelForRole(inv.role)}</span>
                  </div>
                ))}
              </div>
            </details>
          )}
        </div>

        {/* RIGHT — household members + privacy note */}
        <div>
          <div className="card" style={{ marginBottom: 16 }}>
            <h3 className="h-display h3" style={{ marginBottom: 14 }}>In your family</h3>
            <MembersList members={s.members} ownerId={s.household?.owner_id} />

            <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--rule)' }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Kids on this account</div>
              {s.kids.length === 0 ? (
                <div style={{ color: 'var(--ink-soft)', fontSize: 13 }}>None yet — <a href="#/add-kid">add a kid</a>.</div>
              ) : (
                <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
                  {s.kids.map(k => (
                    <div key={k.id} style={{ textAlign: 'center' }}>
                      <window.KidAvatar kid={k} />
                      <div style={{ fontSize: 12, marginTop: 6, fontWeight: 600 }}>{k.name}</div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          <div className="card" style={{ background: 'var(--cream-deep)' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
              <span style={{ fontSize: 28 }}>🔒</span>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15 }}>
                  Your kids' photos stay here.
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 4, lineHeight: 1.45 }}>
                  Photos and names are visible only to people you invite. We never sell data, never share with advertisers, never use family content to train AI.
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .share-grid {
          display: grid;
          grid-template-columns: 1.3fr 1fr;
          gap: 24px;
        }
        @media (max-width: 920px) {
          .share-grid { grid-template-columns: 1fr; }
        }
        .x-btn {
          margin-left: auto;
          width: 24px; height: 24px;
          border-radius: 50%;
          background: rgba(0,0,0,0.05);
          border: 0;
          font-size: 16px; line-height: 1;
          color: inherit; cursor: pointer;
        }
        .copy-pill {
          display: flex; align-items: center; gap: 8px;
          padding: 8px 8px 8px 14px;
          border-radius: 12px;
          background: var(--cream-deep);
          border: 1.5px solid var(--rule-strong);
          font-family: var(--font-mono); font-size: 12.5px;
          color: var(--ink-soft);
        }
        .copy-pill > span {
          flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
        }
      `}</style>
    </div>
  );
}

function PendingRow({ inv, canManage, onRevoke }) {
  const [copied, setCopied] = React.useState(false);
  const link = joinLinkFor(inv.token);
  const copy = async () => {
    try { await navigator.clipboard.writeText(link); setCopied(true); setTimeout(() => setCopied(false), 1500); }
    catch (e) { console.warn(e); }
  };
  const expires = inv.expires_at ? new Date(inv.expires_at) : null;
  const daysLeft = expires ? Math.max(0, Math.round((expires.getTime() - Date.now()) / 86400000)) : null;

  return (
    <div style={{
      padding: 14, borderRadius: 14, background: 'var(--paper)',
      border: '1.5px solid var(--rule-strong)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8, flexWrap: 'wrap' }}>
        <div style={{ fontWeight: 700, fontSize: 14, wordBreak: 'break-all', flex: 1 }}>{inv.invited_email}</div>
        <span className="chip" style={{ background: 'var(--butter-soft)' }}>{labelForRole(inv.role)}</span>
        {daysLeft !== null && (
          <span style={{ fontSize: 12, color: 'var(--ink-faint)' }}>
            {daysLeft === 0 ? 'expires today' : `${daysLeft}d left`}
          </span>
        )}
      </div>
      <div className="copy-pill">
        <span>{link}</span>
        <button className="btn btn-ghost" onClick={copy} style={{ padding: '6px 12px', fontSize: 13 }}>
          {copied ? 'Copied ✓' : 'Copy link'}
        </button>
      </div>
      {canManage && (
        <div style={{ marginTop: 10, textAlign: 'right' }}>
          <button className="btn btn-ghost" onClick={onRevoke}
            style={{ padding: '6px 12px', fontSize: 13, color: 'var(--alert)' }}>
            Revoke
          </button>
        </div>
      )}
    </div>
  );
}

function MembersList({ members, ownerId }) {
  if (!members || !members.length) {
    return <div style={{ color: 'var(--ink-soft)', fontSize: 13 }}>No members yet.</div>;
  }
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      {members.map(m => {
        const isOwner = m.user_id === ownerId;
        const name = m.full_name || m.email || 'Member';
        const initial = (name || '?').trim().charAt(0).toUpperCase();
        return (
          <div key={m.user_id} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div className="kid-avatar" style={{
              background: m.avatar_url ? `url(${m.avatar_url}) center/cover` : 'var(--periwinkle)',
              width: 44, height: 44, fontSize: 16,
            }}>{m.avatar_url ? '' : initial}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{name}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-soft)', wordBreak: 'break-all' }}>{m.email}</div>
            </div>
            <span className="chip" style={isOwner
              ? { background: 'var(--mint-soft)', color: '#156142' }
              : { background: 'var(--cream-deep)', color: 'var(--ink)' }}>
              {isOwner ? 'Owner' : labelForRole(m.role)}
            </span>
          </div>
        );
      })}
    </div>
  );
}

function labelForRole(role) {
  if (role === 'parent') return 'Co-parent';
  if (role === 'helper') return 'Helper';
  if (role === 'viewer') return 'Viewer';
  return role || '—';
}

function flashStyle(kind) {
  const base = {
    marginTop: 14, padding: '10px 14px', borderRadius: 12,
    fontSize: 14, display: 'flex', alignItems: 'center', gap: 10,
    maxWidth: 720,
  };
  if (kind === 'ok') return { ...base, background: 'var(--mint-soft)', color: '#0F4A37' };
  return { ...base, background: 'var(--blush-soft)', color: '#7a2a1f' };
}

window.ShareScreen = ShareScreen;
