/* global React */
// Skillzip Prototype — Shared Components
const { useState, useEffect, useRef } = React;

// ── Icon (Lucide) ────────────────────────────────────────────
function Icon({ name, size = 16, color, style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current || !window.lucide) return;
    const key = name.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('');
    const fn = window.lucide[key];
    if (!fn) return;
    ref.current.innerHTML = '';
    const svg = window.lucide.createElement(fn, { width: size, height: size, strokeWidth: 1.5 });
    if (color) svg.style.color = color;
    svg.style.display = 'block';
    ref.current.appendChild(svg);
  }, [name, size, color]);
  return <span ref={ref} style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0, ...style }} />;
}

// ── Sidebar ──────────────────────────────────────────────────
const SCREEN_NAV = [
  { label: 'Entry', hidden: true, items: [{ code: 'S1', title: 'Create skill entry', key: 'S1' }] },
  { label: 'Path A · Has files', hidden: true, items: [
    { code: 'A1',  title: 'Upload files',       key: 'A1'  },
    { code: 'A2',  title: 'Validate package',   key: 'A2'  },
    { code: 'A7',  title: 'Fix issues',         key: 'A7'  },
    { code: 'A9',  title: 'Preview listing',    key: 'A9'  },
    { code: 'A13', title: 'Publish',            key: 'A13' },
  ]},
  { label: 'Path B · From scratch', hidden: true, items: [
    { code: 'B1', title: 'Create from expertise', key: 'B1' },
    { code: 'B2', title: 'Start here',            key: 'B2' },
    { code: 'B3', title: 'Open Claude',           key: 'B3' },
    { code: 'B4', title: 'Upload to Claude',      key: 'B4' },
    { code: 'B5', title: 'Copy prompt',           key: 'B5' },
    { code: 'B6', title: 'Answer questions',      key: 'B6' },
    { code: 'B7', title: 'Download files',        key: 'B7' },
    { code: 'B8', title: 'Upload back',           key: 'B8' },
  ]},
];

function skillzipUuid() {
  if (window.crypto && window.crypto.randomUUID) return window.crypto.randomUUID();
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

function getSkillzipAnonymousId() {
  let id = window.localStorage.getItem('skillzip_anonymous_id');
  if (!id) {
    id = skillzipUuid();
    window.localStorage.setItem('skillzip_anonymous_id', id);
  }
  return id;
}

function getSkillzipSessionId() {
  let id = window.sessionStorage.getItem('skillzip_session_id');
  if (!id) {
    id = skillzipUuid();
    window.sessionStorage.setItem('skillzip_session_id', id);
  }
  return id;
}

function skillzipTrack(eventName, properties = {}) {
  try {
    fetch('/api/events', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      keepalive: true,
      body: JSON.stringify({
        event_name: eventName,
        anonymous_id: getSkillzipAnonymousId(),
        session_id: getSkillzipSessionId(),
        page_path: window.parent === window ? window.location.pathname : (document.referrer || window.location.pathname),
        referrer: document.referrer || '',
        properties: {
          screen: (window.location.hash || '#S1').slice(1),
          prototype: 'expert-flow-v3',
          ...properties,
        },
      }),
    }).catch(() => {});
  } catch (e) {}
}

const LIFECYCLE_NAV = [
  { id: 'create',  label: 'Create',  icon: 'zap',         comingSoon: false },
  { id: 'publish', label: 'Publish', icon: 'send',         comingSoon: true  },
  { id: 'grow',    label: 'Grow',    icon: 'trending-up',  comingSoon: true  },
  { id: 'earn',    label: 'Earn',    icon: 'dollar-sign',  comingSoon: true  },
  { id: 'connect', label: 'Connect', icon: 'users',        comingSoon: true  },
];

function ProtoSidebar({ current, activeSection, nav }) {
  return (
    <aside className="proto-sidebar">
      <div className="sb-logo">
        <img src="assets/logo-light-mode.jpeg" alt="Skillzip" className="sb-logo-img" />
        <span className="sb-logo-name">Skillzip</span>
      </div>
      <div className="sb-scroll">
        <div style={{ padding: '8px 8px 4px' }}>
          <div className="sb-group-label" style={{ paddingTop: 2, paddingBottom: 6 }}>Skill lifecycle</div>
          {LIFECYCLE_NAV.map(item => {
            const isActive = activeSection === item.id;
            return (
              <div key={item.id}>
                <div
                  className={'sb-lifecycle-item' + (isActive ? ' active' : '') + (item.comingSoon ? ' cs-item' : '')}
                  onClick={() => nav(item.comingSoon ? item.id : 'S1')}
                >
                  <Icon
                    name={item.icon}
                    size={15}
                    color={isActive ? 'var(--color-text-primary)' : 'var(--color-text-tertiary)'}
                  />
                  <span style={{ flex: 1 }}>{item.label}</span>
                  {item.comingSoon && <span className="sb-soon-badge">Soon</span>}
                </div>
                {item.id === 'create' && isActive && (
                  <div className="sb-subnav">
                    {SCREEN_NAV.filter(g => !g.hidden).map(g => (
                      <div key={g.label} style={{ marginBottom: 2 }}>
                        <div className="sb-group-label" style={{ fontSize: 9.5, paddingLeft: 8 }}>{g.label}</div>
                        {g.items.map(s => (
                          <div
                            key={s.key}
                            className={'sb-item' + (current === s.key ? ' active' : '')}
                            onClick={(e) => { e.stopPropagation(); nav(s.key); }}
                            style={{ paddingLeft: 8, fontSize: 12 }}
                          >
                            <span className="sb-item-code">{s.code}</span>
                            <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.title}</span>
                          </div>
                        ))}
                      </div>
                    ))}
                  </div>
                )}
                {item.id === 'create' && <div className="sb-cs-divider" />}
              </div>
            );
          })}
        </div>
      </div>
      <div className="sb-footer">
        <div className="sb-item">
          <Icon name="settings" size={13} color="var(--color-text-tertiary)" />
          <span>Settings</span>
        </div>
        <div className="sb-item">
          <Icon name="help-circle" size={13} color="var(--color-text-tertiary)" />
          <span>Help &amp; docs</span>
        </div>
      </div>
    </aside>
  );
}

// ── Topbar ───────────────────────────────────────────────────
function WaitlistModal({ onClose }) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState('');

  function submit(e) {
    e.preventDefault();
    const cleanEmail = email.trim().toLowerCase();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(cleanEmail)) {
      setError('Enter a valid email.');
      return;
    }
    setStatus('loading');
    setError('');
    skillzipTrack('waitlist_form_submitted', { form_id: 'expert_flow_waitlist' });
    fetch('/api/waitlist', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name,
        email: cleanEmail,
        persona: 'expert',
        source: 'expert-flow-v3',
      }),
    })
      .then(async res => {
        const data = await res.json().catch(() => ({}));
        if (!res.ok) throw new Error(data.error || 'Could not join waitlist.');
        setStatus('success');
        skillzipTrack('waitlist_form_succeeded', { form_id: 'expert_flow_waitlist', waitlist_id: data.id });
      })
      .catch(err => {
        setStatus('error');
        setError(err.message || 'Could not join waitlist.');
        skillzipTrack('waitlist_form_failed', { form_id: 'expert_flow_waitlist', error: err.message || 'unknown' });
      });
  }

  return (
    <div className="waitlist-backdrop" role="dialog" aria-modal="true">
      <div className="waitlist-modal">
        <button className="waitlist-close" onClick={onClose} aria-label="Close waitlist">
          <Icon name="x" size={16} />
        </button>
        {status === 'success' ? (
          <div className="waitlist-success">
            <div className="waitlist-success-icon"><Icon name="check" size={22} color="#16A34A" /></div>
            <h2>You're on the list</h2>
            <p>We saved your email and will reach out when expert publishing opens wider.</p>
            <BtnPrimary onClick={onClose}>Back to flow</BtnPrimary>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div className="waitlist-kicker">Skillzip expert access</div>
            <h2>Join the expert waitlist</h2>
            <p>Get notified when the next publishing slots, Shield scan updates, and buyer analytics ship.</p>
            <div className="field">
              <label>Name</label>
              <input
                className="input"
                value={name}
                onFocus={() => skillzipTrack('waitlist_form_started', { form_id: 'expert_flow_waitlist' })}
                onChange={e => setName(e.target.value)}
                placeholder="Your name"
              />
            </div>
            <div className="field">
              <label>Email</label>
              <input
                className="input"
                value={email}
                onFocus={() => skillzipTrack('waitlist_form_started', { form_id: 'expert_flow_waitlist' })}
                onChange={e => setEmail(e.target.value)}
                placeholder="you@example.com"
                required
              />
            </div>
            {error && <div className="form-error">{error}</div>}
            <div className="waitlist-actions">
              <BtnGhost onClick={onClose}>Cancel</BtnGhost>
              <button className="btn btn-primary" disabled={status === 'loading'} type="submit">
                {status === 'loading' ? 'Saving...' : 'Join waitlist'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function ProtoTopbar({ crumbs, onPrev, onNext, idx, total, hideNav, section }) {
  const [waitlistOpen, setWaitlistOpen] = useState(false);
  const sectionLabels = { create: 'Create', publish: 'Publish', grow: 'Grow', earn: 'Earn', connect: 'Connect' };
  const sectionLabel = sectionLabels[section] || 'Create';
  return (
    <>
    <header className="proto-topbar">
      <div className="tb-crumb">
        <span className="tb-crumb-dim">Skillzip</span>
        <span className="tb-crumb-sep">/</span>
        <span className="tb-crumb-dim">{sectionLabel}</span>
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            <span className="tb-crumb-sep">/</span>
            <span className={i === crumbs.length - 1 ? 'tb-crumb-active' : 'tb-crumb-dim'}>{c}</span>
          </React.Fragment>
        ))}
      </div>
      <div className="tb-actions">
        <button className="tb-btn" title="Feedback"><Icon name="message-square" size={13} />Feedback</button>
        <button className="tb-btn" title="Docs"><Icon name="book-open" size={13} />Docs</button>
        <button
          className="tb-btn tb-waitlist-btn"
          title="Join waitlist"
          onClick={() => {
            setWaitlistOpen(true);
            skillzipTrack('cta_clicked', { button_id: 'expert_flow_join_waitlist', component_id: 'topbar' });
          }}
        >
          Join waitlist
        </button>
        {!hideNav && (
          <>
            <div className="tb-sep" />
            <button className="tb-btn" onClick={onPrev} disabled={idx === 0} title="Previous screen (←)">
              <Icon name="chevron-left" size={14} />
            </button>
            <span className="tb-counter">{idx + 1} / {total}</span>
            <button className="tb-btn" onClick={onNext} disabled={idx === total - 1} title="Next screen (→)">
              <Icon name="chevron-right" size={14} />
            </button>
          </>
        )}
        <div className="tb-sep" />
        <div className="tb-avatar">SK</div>
      </div>
    </header>
    {waitlistOpen && <WaitlistModal onClose={() => setWaitlistOpen(false)} />}
    </>
  );
}

// ── StepBar ──────────────────────────────────────────────────
function StepBar({ steps, current }) {
  return (
    <div className="stepper">
      {steps.map((label, i) => {
        const state = i < current ? 'done' : i === current ? 'active' : 'future';
        return (
          <React.Fragment key={i}>
            {i > 0 && <div className={'step-line' + (i <= current ? ' done' : '')} />}
            <div className="step-node">
              <div className={'step-dot ' + state}>
                {state === 'done' ? <Icon name="check" size={11} color="#fff" /> : i + 1}
              </div>
              <span className={'step-lbl ' + state}>{label}</span>
            </div>
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ── Screen Header ────────────────────────────────────────────
function ScreenHeader({ tag, title, sub, steps, step }) {
  return (
    <div style={{ marginBottom: 4 }}>
      {steps && <StepBar steps={steps} current={step} />}
      {tag && <div className="page-tag">{tag}</div>}
      <h1 className="page-title">{title}</h1>
      {sub && <p className="page-sub">{sub}</p>}
    </div>
  );
}

// ── Footer Bar ───────────────────────────────────────────────
function FootBar({ left, meta, right }) {
  return (
    <div className="foot-bar">
      <div className="foot-left">
        {left}
        {meta && <span className="foot-meta">{meta}</span>}
      </div>
      <div className="foot-right">{right}</div>
    </div>
  );
}

// ── Buttons ──────────────────────────────────────────────────
function BtnPrimary({ children, onClick, icon, size }) {
  const [p, setP] = useState(false);
  const cls = `btn btn-primary${size === 'sm' ? ' btn-sm' : size === 'lg' ? ' btn-lg' : ''}`;
  return (
    <button className={cls} onClick={onClick}
      onMouseDown={() => setP(true)} onMouseUp={() => setP(false)} onMouseLeave={() => setP(false)}
      style={{ transform: p ? 'scale(0.97)' : 'scale(1)' }}>
      {icon && <Icon name={icon} size={13} color="#fff" />}{children}
    </button>
  );
}
function BtnGhost({ children, onClick, icon, size }) {
  return (
    <button className={`btn btn-ghost${size === 'sm' ? ' btn-sm' : ''}`} onClick={onClick}>
      {icon && <Icon name={icon} size={13} />}{children}
    </button>
  );
}
function BtnMuted({ children, onClick, icon, size }) {
  return (
    <button className={`btn btn-muted${size === 'sm' ? ' btn-sm' : ''}`} onClick={onClick}>
      {icon && <Icon name={icon} size={13} color="var(--color-text-secondary)" />}{children}
    </button>
  );
}
function BtnAccent({ children, onClick, icon, size }) {
  const [p, setP] = useState(false);
  const cls = `btn btn-accent${size === 'sm' ? ' btn-sm' : size === 'lg' ? ' btn-lg' : ''}`;
  return (
    <button className={cls} onClick={onClick}
      onMouseDown={() => setP(true)} onMouseUp={() => setP(false)} onMouseLeave={() => setP(false)}
      style={{ transform: p ? 'scale(0.97)' : 'scale(1)' }}>
      {icon && <Icon name={icon} size={13} color="#fff" />}{children}
    </button>
  );
}
function BtnPublish({ children, onClick, icon }) {
  const [p, setP] = useState(false);
  return (
    <button className="btn btn-publish" onClick={onClick}
      onMouseDown={() => setP(true)} onMouseUp={() => setP(false)} onMouseLeave={() => setP(false)}
      style={{ transform: p ? 'scale(0.97)' : 'scale(1)', borderRadius: 'var(--radius-md)' }}>
      {icon && <Icon name={icon} size={14} color="#fff" />}{children}
    </button>
  );
}

// ── Badge ────────────────────────────────────────────────────
function Badge({ variant = 'opt', children }) {
  return <span className={`badge badge-${variant}`}>{children}</span>;
}

// ── File Row ─────────────────────────────────────────────────
function FileRow({ name, meta, status }) {
  const varMap = { valid: 'ok', missing: 'bad', optional: 'opt', required: 'req', draft: 'draft', runtime: 'neutral', 'buyer page': 'neutral', listing: 'neutral' };
  const iconMap = { valid: 'file-check', missing: 'file-x', optional: 'file', required: 'file-text', draft: 'file-edit', runtime: 'file-text', 'buyer page': 'file-text', listing: 'file-text' };
  const colorMap = { valid: '#22C55E', missing: '#EF4444', optional: 'var(--color-text-tertiary)', required: '#2563EB', draft: '#B45309', runtime: 'var(--color-text-tertiary)', 'buyer page': 'var(--color-text-tertiary)', listing: 'var(--color-text-tertiary)' };
  return (
    <div className="filerow">
      <div className="fr-icon">
        <Icon name={iconMap[status] || 'file'} size={13} color={colorMap[status] || 'var(--color-text-tertiary)'} />
      </div>
      <span className="fr-name">{name}</span>
      {meta && <span className="fr-meta">{meta}</span>}
      {status && <Badge variant={varMap[status] || 'opt'}>{status}</Badge>}
    </div>
  );
}

// ── Code Block ───────────────────────────────────────────────
function CodeBlock({ children }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    try { navigator.clipboard.writeText(children); } catch(e) {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  return (
    <div className="codeblock">
      <button className={'copy-btn' + (copied ? ' copied' : '')} onClick={copy}>
        {copied ? 'COPIED' : 'COPY'}
      </button>
      {children}
    </div>
  );
}

// ── Check Item ───────────────────────────────────────────────
function CheckItem({ done, children }) {
  return (
    <div className={'chk' + (done ? ' done' : '')}>
      <div className="chk-box">{done && <Icon name="check" size={11} color="#fff" />}</div>
      <span>{children}</span>
    </div>
  );
}

// ── Segment Control ──────────────────────────────────────────
function Segment({ options, value, onChange }) {
  return (
    <div className="segment">
      {options.map(opt => (
        <div key={opt} className={'seg-btn' + (value === opt ? ' active' : '')} onClick={() => onChange(opt)}>{opt}</div>
      ))}
    </div>
  );
}

// ── Tabs ─────────────────────────────────────────────────────
function Tabs({ tabs, active, onChange }) {
  return (
    <div className="tabs">
      {tabs.map(t => (
        <div key={t} className={'tab' + (active === t ? ' active' : '')} onClick={() => onChange(t)}>{t}</div>
      ))}
    </div>
  );
}

// Export all
Object.assign(window, {
  Icon, ProtoSidebar, ProtoTopbar, StepBar, ScreenHeader,
  FootBar, BtnPrimary, BtnGhost, BtnMuted, BtnAccent, BtnPublish,
  Badge, FileRow, CodeBlock, CheckItem, Segment, Tabs,
  skillzipTrack, getSkillzipAnonymousId,
});
