// Bio tab — manage socials and links in one place, changes save instantly.

const { useState: useS_bio } = React;

const BIO_PLATFORMS = [
  { icon: 'IG', label: 'Instagram',   placeholder: '@yourhandle',    tile: 'tileIG' },
  { icon: 'TT', label: 'TikTok',      placeholder: '@yourhandle',    tile: 'tileTT' },
  { icon: 'FB', label: 'Facebook',    placeholder: 'Your Page name', tile: 'tileFB' },
  { icon: 'YT', label: 'YouTube',     placeholder: '@yourchannel',   tile: 'tileYT' },
  { icon: 'X',  label: 'X (Twitter)', placeholder: '@yourhandle',    tile: 'tileX'  },
  { icon: 'LI', label: 'LinkedIn',    placeholder: 'Your name/page', tile: 'tileLI' },
];

function BioScreen({ profile, onUpdateProfile, onEditProfile, onBack }) {
  const [addingSocial, setAddingSocial] = useS_bio(false);
  const [addingLink,   setAddingLink]   = useS_bio(false);
  const [editSocialIdx, setEditSocialIdx] = useS_bio(null);
  const [editLinkIdx,   setEditLinkIdx]   = useS_bio(null);

  const socials = profile.socials || [];
  const links   = profile.links   || [];

  // ── Socials actions ────────────────────────────────────────
  const addSocial = (platform, handle) => {
    const id = platform.icon.toLowerCase() + '_' + Date.now();
    const next = [...socials, { id, label: platform.label, handle: handle.trim(), icon: platform.icon, tile: platform.tile }];
    onUpdateProfile({ ...profile, socials: next });
    setAddingSocial(false);
  };

  const removeSocial = (idx) => {
    onUpdateProfile({ ...profile, socials: socials.filter((_, i) => i !== idx) });
  };

  const updateSocialHandle = (idx, handle) => {
    const next = socials.map((s, i) => i === idx ? { ...s, handle } : s);
    onUpdateProfile({ ...profile, socials: next });
    setEditSocialIdx(null);
  };

  // ── Links actions ──────────────────────────────────────────
  const addLink = ({ label, sub, href, primary }) => {
    const id = 'link_' + Date.now();
    const next = [...links, { id, label, sub, href: href || '#', primary }];
    onUpdateProfile({ ...profile, links: next });
    setAddingLink(false);
  };

  const removeLink = (idx) => {
    onUpdateProfile({ ...profile, links: links.filter((_, i) => i !== idx) });
  };

  const updateLink = (idx, updated) => {
    const next = links.map((l, i) => i === idx ? { ...l, ...updated } : l);
    onUpdateProfile({ ...profile, links: next });
    setEditLinkIdx(null);
  };

  const toggleLinkPrimary = (idx) => {
    const next = links.map((l, i) => i === idx ? { ...l, primary: !l.primary } : l);
    onUpdateProfile({ ...profile, links: next });
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: HUUL_TOKENS.color.bg }}>
      <div style={{ padding: '54px 16px 8px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.5 }}>Your Page</div>
          <div style={{ fontSize: 13.5, color: HUUL_TOKENS.color.ink3, marginTop: 2 }}>
            Manage what people see on your link-in-bio.
          </div>
        </div>
        {onBack && (
          <button onClick={onBack} style={{
            border: 'none', background: 'transparent',
            color: HUUL_TOKENS.color.accent,
            fontSize: 16, fontWeight: 600, cursor: 'pointer',
            fontFamily: HUUL_TOKENS.font.stack, marginTop: 4,
          }}>Done</button>
        )}
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '10px 16px 100px' }}>

        {/* Profile summary card */}
        <div style={{
          background: '#fff', borderRadius: 20, padding: 14,
          display: 'flex', alignItems: 'center', gap: 12,
          boxShadow: HUUL_TOKENS.shadow.card, marginBottom: 20,
        }}>
          <Avatar profile={profile} size={52}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: -0.2 }}>{profile.businessName}</div>
            <div style={{ fontSize: 13, color: HUUL_TOKENS.color.ink3, marginTop: 2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {profile.bio || 'No bio yet'}
            </div>
          </div>
          <IconButton icon={<IconEdit size={16}/>} onClick={onEditProfile} bg="rgba(0,0,0,0.05)"/>
        </div>

        {/* ── Socials ─────────────────────────────────────── */}
        <BioSection title="Socials" subtitle="Your social media accounts">
          {socials.length > 0 && (
            <div style={{
              background: '#fff', borderRadius: 16,
              boxShadow: HUUL_TOKENS.shadow.card, marginBottom: 10, overflow: 'hidden',
            }}>
              {socials.map((s, i) => (
                <BioSocialRow
                  key={s.id}
                  social={s}
                  isEditing={editSocialIdx === i}
                  onEdit={() => setEditSocialIdx(editSocialIdx === i ? null : i)}
                  onUpdateHandle={(h) => updateSocialHandle(i, h)}
                  onRemove={() => removeSocial(i)}
                  isLast={i === socials.length - 1}
                />
              ))}
            </div>
          )}

          {!addingSocial ? (
            <AddRowButton
              label={socials.length === 0 ? 'Add your first social account' : 'Add another social'}
              onClick={() => { setAddingSocial(true); setAddingLink(false); }}
            />
          ) : (
            <BioAddSocialPanel
              existing={socials}
              onAdd={addSocial}
              onCancel={() => setAddingSocial(false)}
            />
          )}
        </BioSection>

        {/* ── Links ───────────────────────────────────────── */}
        <BioSection title="Links" subtitle="Buttons shown on your profile">
          {links.length > 0 && (
            <div style={{
              background: '#fff', borderRadius: 16,
              boxShadow: HUUL_TOKENS.shadow.card, marginBottom: 10, overflow: 'hidden',
            }}>
              {links.map((l, i) => (
                <BioLinkRow
                  key={l.id}
                  link={l}
                  isEditing={editLinkIdx === i}
                  onEdit={() => setEditLinkIdx(editLinkIdx === i ? null : i)}
                  onUpdate={(u) => updateLink(i, u)}
                  onRemove={() => removeLink(i)}
                  onTogglePrimary={() => toggleLinkPrimary(i)}
                  isLast={i === links.length - 1}
                />
              ))}
            </div>
          )}

          {!addingLink ? (
            <AddRowButton
              label={links.length === 0 ? 'Add your first link' : 'Add another link'}
              onClick={() => { setAddingLink(true); setAddingSocial(false); }}
            />
          ) : (
            <BioAddLinkPanel onAdd={addLink} onCancel={() => setAddingLink(false)} />
          )}
        </BioSection>

      </div>
    </div>
  );
}

// ── Shared layout ──────────────────────────────────────────────
function BioSection({ title, subtitle, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{ marginBottom: 10, paddingLeft: 4 }}>
        <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: -0.3 }}>{title}</div>
        <div style={{ fontSize: 12.5, color: HUUL_TOKENS.color.ink3, marginTop: 2 }}>{subtitle}</div>
      </div>
      {children}
    </div>
  );
}

function AddRowButton({ label, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', height: 48, borderRadius: 14, border: `1.5px dashed ${HUUL_TOKENS.color.sep}`,
      background: 'transparent', color: HUUL_TOKENS.color.accent,
      fontSize: 14.5, fontWeight: 600, cursor: 'pointer',
      fontFamily: HUUL_TOKENS.font.stack,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    }}>
      <IconPlus size={16}/> {label}
    </button>
  );
}

// ── Social row ─────────────────────────────────────────────────
function BioSocialRow({ social, isEditing, onEdit, onUpdateHandle, onRemove, isLast }) {
  const [draft, setDraft] = useS_bio(social.handle);
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px' }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10, flexShrink: 0,
          background: HUUL_TOKENS.color[social.tile] || '#F2F2F4',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <SocialGlyph icon={social.icon} size={18}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{social.label}</div>
          <div style={{ fontSize: 12.5, color: HUUL_TOKENS.color.ink3, marginTop: 1,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {social.handle}
          </div>
        </div>
        <IconButton icon={<IconEdit size={14}/>} onClick={onEdit} size={30} bg="rgba(0,0,0,0.05)"/>
        <IconButton icon={<IconTrash size={14}/>} onClick={onRemove} size={30}
          bg="rgba(255,59,48,0.08)" style={{ color: HUUL_TOKENS.color.danger }}/>
      </div>
      {isEditing && (
        <div style={{ padding: '0 14px 12px', display: 'flex', gap: 8 }}>
          <TextField value={draft} onChange={setDraft} placeholder="Handle or name"
            style={{ flex: 1, boxShadow: 'none', background: 'rgba(0,0,0,0.04)', minHeight: 42 }}/>
          <button onClick={() => onUpdateHandle(draft)} style={{
            border: 'none', background: HUUL_TOKENS.color.accent, color: '#fff',
            borderRadius: 10, padding: '0 14px', fontSize: 13.5, fontWeight: 600,
            cursor: 'pointer', fontFamily: HUUL_TOKENS.font.stack, flexShrink: 0,
          }}>Done</button>
        </div>
      )}
      {!isLast && <div style={{ height: 1, background: HUUL_TOKENS.color.sep, margin: '0 14px' }}/>}
    </div>
  );
}

// ── Add social inline panel ────────────────────────────────────
function BioAddSocialPanel({ existing, onAdd, onCancel }) {
  const [selected, setSelected] = useS_bio(null);
  const [handle, setHandle]     = useS_bio('');
  const existingIcons = existing.map(s => s.icon);
  const available = BIO_PLATFORMS.filter(p => !existingIcons.includes(p.icon));
  const canAdd = selected && handle.trim().length >= 1;

  return (
    <div style={{ background: '#fff', borderRadius: 16, padding: 14, boxShadow: HUUL_TOKENS.shadow.card }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: HUUL_TOKENS.color.ink2, marginBottom: 10 }}>
        Choose platform
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 12 }}>
        {available.map(p => (
          <button key={p.icon} onClick={() => { setSelected(p); setHandle(''); }} style={{
            border: `2px solid ${selected?.icon === p.icon ? HUUL_TOKENS.color.accent : 'transparent'}`,
            borderRadius: 12, background: selected?.icon === p.icon
              ? 'rgba(10,132,255,0.06)' : HUUL_TOKENS.color[p.tile] || '#F2F2F4',
            padding: '9px 10px', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 8,
            fontFamily: HUUL_TOKENS.font.stack, transition: 'border-color 120ms',
          }}>
            <SocialGlyph icon={p.icon} size={20}/>
            <span style={{ fontSize: 13, fontWeight: 600, color: HUUL_TOKENS.color.ink }}>{p.label}</span>
          </button>
        ))}
        {available.length === 0 && (
          <div style={{ gridColumn: '1/-1', fontSize: 13, color: HUUL_TOKENS.color.ink3, padding: '4px' }}>
            All platforms already added.
          </div>
        )}
      </div>
      {selected && (
        <div style={{ marginBottom: 12 }}>
          <TextField value={handle} onChange={setHandle}
            placeholder={selected.placeholder} autoFocus
            style={{ boxShadow: 'none', background: 'rgba(0,0,0,0.04)' }}/>
        </div>
      )}
      <div style={{ display: 'flex', gap: 8 }}>
        <GhostButton onClick={onCancel} style={{ flex: 1, justifyContent: 'center' }}>Cancel</GhostButton>
        <button onClick={canAdd ? () => onAdd(selected, handle) : undefined} disabled={!canAdd} style={{
          flex: 1, height: 44, border: 'none', borderRadius: 12,
          background: canAdd ? HUUL_TOKENS.color.accent : 'rgba(0,0,0,0.07)',
          color: canAdd ? '#fff' : HUUL_TOKENS.color.ink4,
          fontSize: 15, fontWeight: 600, cursor: canAdd ? 'pointer' : 'not-allowed',
          fontFamily: HUUL_TOKENS.font.stack,
        }}>Add</button>
      </div>
    </div>
  );
}

// ── Link row ───────────────────────────────────────────────────
function BioLinkRow({ link, isEditing, onEdit, onUpdate, onRemove, onTogglePrimary, isLast }) {
  const [label, setLabel] = useS_bio(link.label);
  const [sub,   setSub]   = useS_bio(link.sub || '');
  const [href,  setHref]  = useS_bio(link.href || '');
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px' }}>
        <button onClick={onTogglePrimary} title="Toggle primary" style={{
          border: 'none', cursor: 'pointer', padding: 0, background: 'transparent', flexShrink: 0,
        }}>
          <div style={{
            width: 12, height: 12, borderRadius: 6,
            background: link.primary ? HUUL_TOKENS.color.accent : HUUL_TOKENS.color.ink4,
            transition: 'background 150ms',
          }}/>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{link.label}</div>
          {link.sub && (
            <div style={{ fontSize: 12.5, color: HUUL_TOKENS.color.ink3, marginTop: 1,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{link.sub}</div>
          )}
        </div>
        <IconButton icon={<IconEdit size={14}/>} onClick={onEdit} size={30} bg="rgba(0,0,0,0.05)"/>
        <IconButton icon={<IconTrash size={14}/>} onClick={onRemove} size={30}
          bg="rgba(255,59,48,0.08)" style={{ color: HUUL_TOKENS.color.danger }}/>
      </div>
      {isEditing && (
        <div style={{ padding: '0 14px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <TextField value={label} onChange={setLabel} placeholder="Button label"
            style={{ boxShadow: 'none', background: 'rgba(0,0,0,0.04)' }}/>
          <TextField value={sub} onChange={setSub} placeholder="Subtitle (optional)"
            style={{ boxShadow: 'none', background: 'rgba(0,0,0,0.04)' }}/>
          <TextField value={href} onChange={setHref} placeholder="URL (https://…)"
            style={{ boxShadow: 'none', background: 'rgba(0,0,0,0.04)' }}/>
          <button onClick={() => onUpdate({ label, sub, href })} style={{
            border: 'none', background: HUUL_TOKENS.color.accent, color: '#fff',
            borderRadius: 10, height: 42, fontSize: 14, fontWeight: 600,
            cursor: 'pointer', fontFamily: HUUL_TOKENS.font.stack,
          }}>Done</button>
        </div>
      )}
      {!isLast && <div style={{ height: 1, background: HUUL_TOKENS.color.sep, margin: '0 14px' }}/>}
    </div>
  );
}

// ── Add link inline panel ──────────────────────────────────────
function BioAddLinkPanel({ onAdd, onCancel }) {
  const [label,   setLabel]   = useS_bio('');
  const [sub,     setSub]     = useS_bio('');
  const [href,    setHref]    = useS_bio('');
  const [primary, setPrimary] = useS_bio(false);
  const canAdd = label.trim().length >= 1;

  return (
    <div style={{ background: '#fff', borderRadius: 16, padding: 14, boxShadow: HUUL_TOKENS.shadow.card }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: HUUL_TOKENS.color.ink2, marginBottom: 10 }}>
        New link
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 12 }}>
        <TextField value={label} onChange={setLabel} placeholder="Button label (e.g. Visit our website)"
          autoFocus style={{ boxShadow: 'none', background: 'rgba(0,0,0,0.04)' }}/>
        <TextField value={sub} onChange={setSub} placeholder="Subtitle (optional)"
          style={{ boxShadow: 'none', background: 'rgba(0,0,0,0.04)' }}/>
        <TextField value={href} onChange={setHref} placeholder="URL (https://…)"
          style={{ boxShadow: 'none', background: 'rgba(0,0,0,0.04)' }}/>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          background: 'rgba(0,0,0,0.03)', borderRadius: 10, padding: '9px 12px',
        }}>
          <div style={{ fontSize: 13.5, fontWeight: 500 }}>Highlight as primary (blue)</div>
          <div onClick={() => setPrimary(p => !p)} style={{ cursor: 'pointer' }}>
            <div style={{
              width: 40, height: 24, borderRadius: 12,
              background: primary ? HUUL_TOKENS.color.accent : 'rgba(0,0,0,0.14)',
              position: 'relative', transition: 'background 180ms',
            }}>
              <div style={{
                position: 'absolute', top: 2, left: primary ? 18 : 2,
                width: 20, height: 20, borderRadius: 10, background: '#fff',
                boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
                transition: 'left 180ms cubic-bezier(.4,0,.2,1)',
              }}/>
            </div>
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <GhostButton onClick={onCancel} style={{ flex: 1, justifyContent: 'center' }}>Cancel</GhostButton>
        <button onClick={canAdd ? () => onAdd({ label: label.trim(), sub: sub.trim(), href: href.trim() || '#', primary }) : undefined}
          disabled={!canAdd} style={{
            flex: 1, height: 44, border: 'none', borderRadius: 12,
            background: canAdd ? HUUL_TOKENS.color.accent : 'rgba(0,0,0,0.07)',
            color: canAdd ? '#fff' : HUUL_TOKENS.color.ink4,
            fontSize: 15, fontWeight: 600, cursor: canAdd ? 'pointer' : 'not-allowed',
            fontFamily: HUUL_TOKENS.font.stack,
          }}>Add</button>
      </div>
    </div>
  );
}

window.BioScreen = BioScreen;
