// Socials editor — add, remove, and edit social media accounts.

const { useState: useS_se, useRef: useR_se } = React;

const SOCIAL_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 SocialsEditorScreen({ profile, onSave, onClose }) {
  const [socials, setSocials] = useS_se(
    (profile.socials || []).map(s => ({ ...s, _key: s.id }))
  );
  const [adding, setAdding]   = useS_se(false);
  const [editIdx, setEditIdx] = useS_se(null);

  const removeItem = (idx) => {
    setSocials(s => s.filter((_, i) => i !== idx));
  };

  const addItem = (platform, handle) => {
    const id = platform.icon.toLowerCase() + '_' + Date.now();
    setSocials(s => [...s, {
      id,
      _key: id,
      label:  platform.label,
      handle: handle.trim(),
      icon:   platform.icon,
      tile:   platform.tile,
    }]);
    setAdding(false);
  };

  const updateHandle = (idx, handle) => {
    setSocials(s => s.map((item, i) => i === idx ? { ...item, handle } : item));
    setEditIdx(null);
  };

  const handleSave = () => {
    onSave({ ...profile, socials: socials.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 }}>Socials</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' }}>

        {/* Current socials list */}
        {socials.length > 0 && (
          <div style={{
            background: '#fff', borderRadius: 20,
            boxShadow: HUUL_TOKENS.shadow.card, marginBottom: 14, overflow: 'hidden',
          }}>
            {socials.map((s, i) => (
              <SocialRow
                key={s._key}
                social={s}
                isEditing={editIdx === i}
                onEdit={() => setEditIdx(editIdx === i ? null : i)}
                onUpdateHandle={(h) => updateHandle(i, h)}
                onRemove={() => removeItem(i)}
                isLast={i === socials.length - 1}
              />
            ))}
          </div>
        )}

        {/* Empty state */}
        {socials.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 socials yet</div>
            <div style={{ fontSize: 13.5, color: HUUL_TOKENS.color.ink3, lineHeight: 1.45 }}>
              Add your social accounts so customers can follow you.
            </div>
          </div>
        )}

        {/* Add new social */}
        {!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 social account
          </button>
        ) : (
          <AddSocialPanel platforms={SOCIAL_PLATFORMS} onAdd={addItem} onCancel={() => setAdding(false)} existing={socials} />
        )}
      </div>
    </div>
  );
}

function SocialRow({ social, isEditing, onEdit, onUpdateHandle, onRemove, isLast }) {
  const [draft, setDraft] = useS_se(social.handle);

  return (
    <div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
      }}>
        <div style={{
          width: 38, height: 38, borderRadius: 10, flexShrink: 0,
          background: HUUL_TOKENS.color[social.tile] || '#F2F2F4',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <SocialGlyph icon={social.icon} size={20} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14.5, fontWeight: 600 }}>{social.label}</div>
          <div style={{ fontSize: 13, color: HUUL_TOKENS.color.ink3, marginTop: 1,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {social.handle}
          </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', gap: 8 }}>
          <TextField
            value={draft}
            onChange={setDraft}
            placeholder="Handle or name"
            style={{ flex: 1, boxShadow: 'none', background: 'rgba(0,0,0,0.04)', minHeight: 44 }}
          />
          <button onClick={() => onUpdateHandle(draft)} style={{
            border: 'none', background: HUUL_TOKENS.color.accent, color: '#fff',
            borderRadius: 12, padding: '0 14px', fontSize: 14, 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 16px' }} />
      )}
    </div>
  );
}

function AddSocialPanel({ platforms, onAdd, onCancel, existing }) {
  const [selected, setSelected] = useS_se(null);
  const [handle, setHandle]     = useS_se('');

  const existingIcons = existing.map(s => s.icon);
  const available = platforms.filter(p => !existingIcons.includes(p.icon));

  const canAdd = selected && handle.trim().length >= 1;

  return (
    <div style={{
      background: '#fff', borderRadius: 20, padding: 16,
      boxShadow: HUUL_TOKENS.shadow.card,
    }}>
      <HuulLabel>Choose platform</HuulLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
        {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: 14, background: selected?.icon === p.icon
              ? 'rgba(10,132,255,0.06)'
              : HUUL_TOKENS.color[p.tile] || '#F2F2F4',
            padding: '10px 12px', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 10,
            fontFamily: HUUL_TOKENS.font.stack,
            transition: 'border-color 120ms, background 120ms',
          }}>
            <SocialGlyph icon={p.icon} size={22} />
            <span style={{ fontSize: 13.5, fontWeight: 600, color: HUUL_TOKENS.color.ink }}>{p.label}</span>
          </button>
        ))}
        {available.length === 0 && (
          <div style={{
            gridColumn: '1/-1', fontSize: 13.5, color: HUUL_TOKENS.color.ink3,
            padding: '8px 4px',
          }}>
            All platforms already added.
          </div>
        )}
      </div>

      {selected && (
        <div style={{ marginBottom: 14 }}>
          <HuulLabel>{selected.label} handle / name</HuulLabel>
          <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>
  );
}

window.SocialsEditorScreen = SocialsEditorScreen;
