// Links editor — add, remove, and edit custom link buttons shown on the profile.

const { useState: useS_le } = React;

function LinksEditorScreen({ profile, onSave, onClose }) {
  const [links, setLinks]   = useS_le(
    (profile.links || []).map(l => ({ ...l, _key: l.id }))
  );
  const [adding, setAdding] = useS_le(false);
  const [editIdx, setEditIdx] = useS_le(null);

  const removeItem = (idx) => setLinks(l => l.filter((_, i) => i !== idx));

  const addItem = ({ label, sub, href, primary }) => {
    const id = 'link_' + Date.now();
    setLinks(l => [...l, { id, _key: id, label, sub, href, primary }]);
    setAdding(false);
  };

  const updateItem = (idx, updated) => {
    setLinks(l => l.map((item, i) => i === idx ? { ...item, ...updated } : item));
    setEditIdx(null);
  };

  const togglePrimary = (idx) => {
    setLinks(l => l.map((item, i) => i === idx ? { ...item, primary: !item.primary } : item));
  };

  const handleSave = () => {
    onSave({ ...profile, links: links.map(({ _key, ...rest }) => rest) });
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: HUUL_TOKENS.color.bg }}>
      {/* Nav bar */}
      <div style={{ padding: '54px 16px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <GhostButton onClick={onClose}>Cancel</GhostButton>
        <div style={{ fontSize: 16, fontWeight: 600 }}>Links</div>
        <button
          onClick={handleSave}
          style={{
            border: 'none', background: 'transparent',
            color: HUUL_TOKENS.color.accent,
            fontSize: 16, fontWeight: 600, cursor: 'pointer',
            fontFamily: HUUL_TOKENS.font.stack,
          }}>Save</button>
      </div>

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

        {links.length > 0 && (
          <div style={{
            background: '#fff', borderRadius: 20,
            boxShadow: HUUL_TOKENS.shadow.card, marginBottom: 14, overflow: 'hidden',
          }}>
            {links.map((l, i) => (
              <LinkRow
                key={l._key}
                link={l}
                isEditing={editIdx === i}
                onEdit={() => setEditIdx(editIdx === i ? null : i)}
                onUpdate={(u) => updateItem(i, u)}
                onRemove={() => removeItem(i)}
                onTogglePrimary={() => togglePrimary(i)}
                isLast={i === links.length - 1}
              />
            ))}
          </div>
        )}

        {links.length === 0 && !adding && (
          <div style={{
            background: '#fff', borderRadius: 20, padding: '28px 20px',
            textAlign: 'center', boxShadow: HUUL_TOKENS.shadow.card, marginBottom: 14,
          }}>
            <div style={{ fontSize: 36, marginBottom: 8 }}>🔗</div>
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>No links yet</div>
            <div style={{ fontSize: 13.5, color: HUUL_TOKENS.color.ink3, lineHeight: 1.45 }}>
              Add links to your website, promotions, or anything you want to share.
            </div>
          </div>
        )}

        {!adding ? (
          <button onClick={() => setAdding(true)} style={{
            width: '100%', height: 50, borderRadius: 14, border: 'none',
            background: HUUL_TOKENS.color.accent, color: '#fff',
            fontSize: 15, fontWeight: 600, cursor: 'pointer',
            fontFamily: HUUL_TOKENS.font.stack,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            boxShadow: HUUL_TOKENS.shadow.btn,
          }}>
            <IconPlus size={18} color="#fff" /> Add link
          </button>
        ) : (
          <AddLinkPanel onAdd={addItem} onCancel={() => setAdding(false)} />
        )}
      </div>
    </div>
  );
}

function LinkRow({ link, isEditing, onEdit, onUpdate, onRemove, onTogglePrimary, isLast }) {
  const [label, setLabel] = useS_le(link.label);
  const [sub, setSub]     = useS_le(link.sub || '');
  const [href, setHref]   = useS_le(link.href || '');

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px' }}>
        {/* primary badge / toggle */}
        <button onClick={onTogglePrimary} title="Toggle primary (blue highlight)" 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.5, 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={15}/>} onClick={onEdit} size={32} bg="rgba(0,0,0,0.05)"/>
        <IconButton icon={<IconTrash size={15}/>} onClick={onRemove} size={32}
          bg="rgba(255,59,48,0.08)" style={{ color: HUUL_TOKENS.color.danger }}/>
      </div>

      {isEditing && (
        <div style={{ padding: '0 16px 14px', 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: 12, 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 16px' }} />
      )}
    </div>
  );
}

function AddLinkPanel({ onAdd, onCancel }) {
  const [label, setLabel]   = useS_le('');
  const [sub, setSub]       = useS_le('');
  const [href, setHref]     = useS_le('');
  const [primary, setPrimary] = useS_le(false);

  const canAdd = label.trim().length >= 1;

  return (
    <div style={{
      background: '#fff', borderRadius: 20, padding: 16,
      boxShadow: HUUL_TOKENS.shadow.card,
    }}>
      <HuulLabel>New link</HuulLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 14 }}>
        <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 (e.g. Limited offer)"
          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)' }} />

        {/* Primary toggle */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          background: 'rgba(0,0,0,0.03)', borderRadius: 12, padding: '10px 14px',
        }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Highlight as primary</div>
            <div style={{ fontSize: 12, color: HUUL_TOKENS.color.ink3, marginTop: 2 }}>Shows as a blue button</div>
          </div>
          <div onClick={() => setPrimary(p => !p)} style={{ cursor: 'pointer' }}>
            <div style={{
              width: 44, height: 26, borderRadius: 13,
              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 ? 20 : 2,
                width: 22, height: 22, borderRadius: 11, 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.LinksEditorScreen = LinksEditorScreen;
