/* Shared building blocks para las pantallas del lab */

// ───── Icons (inline SVG)
const Icon = {
  pivot: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 12L8 4L13 12" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  trendline: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M2 13L14 3" strokeLinecap="round"/><circle cx="2" cy="13" r="1.5" fill="currentColor"/><circle cx="14" cy="3" r="1.5" fill="currentColor"/></svg>,
  channel: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M2 13L14 5M2 11L14 3" strokeLinecap="round"/></svg>,
  horizontal: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M2 8L14 8" strokeLinecap="round"/><circle cx="2" cy="8" r="1.5" fill="currentColor"/><circle cx="14" cy="8" r="1.5" fill="currentColor"/></svg>,
  zone: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><rect x="2" y="6" width="12" height="4" stroke="currentColor" strokeWidth="1.5" fill="currentColor" fillOpacity="0.2"/></svg>,
  fibonacci: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.2"><path d="M2 13L14 13M2 10L14 10M2 7L14 7M2 4L14 4" strokeLinecap="round"/></svg>,
  annotation: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 4h10v6h-3l-2 3l-1-3H3z" strokeLinejoin="round"/></svg>,
  tutor: (s = 16) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="8" cy="6" r="2.5"/><path d="M3 14c0-2.5 2.2-4.5 5-4.5s5 2 5 4.5"/></svg>,
  gloss: (s = 16) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 3h10v10H3z"/><path d="M5 6h6M5 9h4"/></svg>,
  play: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="currentColor"><path d="M4 3l9 5l-9 5z"/></svg>,
  pause: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="currentColor"><rect x="4" y="3" width="3" height="10"/><rect x="9" y="3" width="3" height="10"/></svg>,
  step: (s = 14) => <svg width={s} height={s} viewBox="0 0 16 16" fill="currentColor"><path d="M3 3l7 5l-7 5z"/><rect x="11" y="3" width="2" height="10"/></svg>,
  lock: (s = 12) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="7" width="10" height="7"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/></svg>,
  check: (s = 12) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 8l3 3l7-7" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  warn: (s = 12) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M8 2L14 13H2z" strokeLinejoin="round"/><path d="M8 6v4M8 11.5v.5"/></svg>,
  close: (s = 12) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 4l8 8M12 4l-8 8" strokeLinecap="round"/></svg>,
};

window.Icon = Icon;

// ───── Topbar del shell
function ShellTopbar({ moduleId, episodeId, episodeTitle, percentComplete }) {
  return (
    <div className="shell-topbar">
      <span className="crumb">Finaz</span>
      <span className="crumb-sep">/</span>
      <span className="crumb">C03-A Tendencia</span>
      <span className="crumb-sep">/</span>
      <span className="crumb">{moduleId}</span>
      <span className="crumb-sep">/</span>
      <span className="crumb-current">{episodeId} · {episodeTitle}</span>
      <div className="shell-topbar-right">
        <span style={{ fontSize: 'var(--size-xs)', color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>
          {percentComplete}% completado
        </span>
        <button className="btn btn-ghost btn-icon" title="Glosario">{Icon.gloss(14)}</button>
        <button className="btn btn-ghost btn-icon" title="Tutor">{Icon.tutor(14)}</button>
      </div>
    </div>
  );
}
window.ShellTopbar = ShellTopbar;

// ───── Rail S1→S4
function Rail({ current = 3, completed = [1, 2] }) {
  const steps = [
    { n: 1, label: 'Hook' },
    { n: 2, label: 'Concepto' },
    { n: 3, label: 'Lab' },
    { n: 4, label: 'Transfer' },
  ];
  return (
    <div className="rail">
      {steps.map((s) => (
        <div key={s.n} className={`rail-step ${current === s.n ? 'active' : ''} ${completed.includes(s.n) ? 'complete' : ''}`}>
          <div className="rail-step-num">{completed.includes(s.n) ? Icon.check(13) : s.n}</div>
          <div className="rail-step-label">S{s.n}</div>
        </div>
      ))}
    </div>
  );
}
window.Rail = Rail;

// ───── Toolbar lateral
function LabToolbar({ tools, activeTool, onSelect, episodeUnlock = {} }) {
  /* tools = [{ id, icon, label, group, unlockFrom }] */
  return (
    <div className="lab-toolbar">
      {tools.map((t, i) => {
        if (t.sep) return <div key={`sep-${i}`} className="tool-group-sep" />;
        const locked = t.unlockFrom && !episodeUnlock[t.unlockFrom];
        return (
          <button key={t.id}
            className={`tool-btn ${activeTool === t.id ? 'active' : ''} ${locked ? 'locked' : ''}`}
            onClick={() => !locked && onSelect(activeTool === t.id ? null : t.id)}>
            {t.icon}
            <span className="tool-tooltip">
              {t.label}{locked ? ` · disponible en ${t.unlockFrom}+` : ''}
            </span>
            {locked && <span style={{ position: 'absolute', bottom: 2, right: 4, opacity: 0.5 }}>{Icon.lock(8)}</span>}
          </button>
        );
      })}
    </div>
  );
}
window.LabToolbar = LabToolbar;

// ───── Drawing list (panel lateral)
function DrawingList({ drawings, onRemove, label = 'Tus dibujos' }) {
  const active = drawings.filter((d) => d.state !== 'discarded' && !d.hidden);
  const discarded = drawings.filter((d) => d.state === 'discarded');
  const [showDisc, setShowDisc] = React.useState(false);

  return (
    <div className="side-section">
      <h4>
        {label}
        <span className="count">{active.length}</span>
      </h4>
      <div className="draw-list">
        {active.length === 0 && (
          <div style={{ fontSize: 'var(--size-xs)', color: 'var(--text-muted)', fontStyle: 'italic', padding: '8px 0' }}>
            Aún no has dibujado nada.
          </div>
        )}
        {active.map((d, i) => (
          <div key={d.id || i} className="draw-item">
            <div className="draw-item-icon">{drawingIcon(d)}</div>
            <div>
              <div style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{drawingLabel(d)}</div>
              <div className="draw-item-meta">
                {d.touches != null && (
                  <span className={d.state === 'valid' ? 'ok' : 'warn'}>
                    {d.state === 'valid' ? `✓ ${d.touches} toques` : `⚠ ${d.touches} toques`}
                  </span>
                )}
                {d.state === 'invalid' && <span className="warn">⚠ pivot no validado</span>}
                {d.state === 'valid' && d.touches == null && <span className="ok">✓ validado</span>}
              </div>
            </div>
            {onRemove && <button className="draw-item-remove" onClick={() => onRemove(d)}>×</button>}
          </div>
        ))}
      </div>
      {discarded.length > 0 && (
        <div>
          <div className="draw-collapsed" onClick={() => setShowDisc(!showDisc)}>
            <span>{showDisc ? '▾' : '▸'}</span> Descartadas ({discarded.length})
          </div>
          {showDisc && discarded.map((d, i) => (
            <div key={`disc-${i}`} className="draw-item discarded">
              <div className="draw-item-icon">{drawingIcon(d)}</div>
              <div>
                <div>{drawingLabel(d)}</div>
                <div className="draw-item-meta">descartada</div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
window.DrawingList = DrawingList;

function drawingIcon(d) {
  if (d.type === 'pivot') return Icon.pivot(14);
  if (d.type === 'trendline') return Icon.trendline(14);
  if (d.type === 'channel') return Icon.channel(14);
  if (d.type === 'horizontal') return Icon.horizontal(14);
  if (d.type === 'zone') return Icon.zone(14);
  if (d.type === 'annotation') return Icon.annotation(14);
  return null;
}
function drawingLabel(d) {
  if (d.type === 'pivot') return `Pivot ${d.kind}`;
  if (d.type === 'trendline') return 'Trendline';
  if (d.type === 'channel') return 'Canal';
  if (d.type === 'horizontal') return d.kind === 'support' ? 'Soporte' : 'Resistencia';
  if (d.type === 'zone') return `Zona ${d.kind}`;
  if (d.type === 'annotation') return 'Nota';
  return d.type;
}

// ───── Feedback banner
function FeedbackBanner({ kind = 'neutral', icon, message, quote }) {
  const ic = icon || (kind === 'pass' ? '✓' : kind === 'warn' ? '!' : kind === 'fail' ? '×' : '·');
  return (
    <div className={`feedback-banner ${kind}`}>
      <div className="feedback-icon">{ic}</div>
      <div>
        <div>{message}</div>
        {quote && <div className="feedback-quote">{quote}</div>}
      </div>
    </div>
  );
}
window.FeedbackBanner = FeedbackBanner;

// ───── Conviction picker (1-5)
function ConvictionPicker({ value, onChange, label = 'Convicción' }) {
  return (
    <div>
      <div className="conviction">
        <span className="conviction-label">{label}</span>
        {[1, 2, 3, 4, 5].map((n) => (
          <button key={n} onClick={() => onChange(n)} className={`conviction-dot ${value === n ? 'selected' : ''}`}>{n}</button>
        ))}
      </div>
    </div>
  );
}
window.ConvictionPicker = ConvictionPicker;

// ───── Set de tools por episodio
function trendlineLabTools() {
  return [
    { id: 'pivot', icon: Icon.pivot(16), label: 'Pivot marker', group: 'pivots' },
    { id: 'trendline', icon: Icon.trendline(16), label: 'Trendline', group: 'lines' },
    { id: 'annotation', icon: Icon.annotation(16), label: 'Anotación', group: 'notes' },
    { sep: true },
    { id: 'channel', icon: Icon.channel(16), label: 'Canal', unlockFrom: 'M03' },
    { id: 'horizontal-support', icon: Icon.horizontal(16), label: 'Soporte', unlockFrom: 'M04' },
    { id: 'horizontal-resistance', icon: Icon.horizontal(16), label: 'Resistencia', unlockFrom: 'M04' },
    { id: 'zone', icon: Icon.zone(16), label: 'Zona S/R', unlockFrom: 'M04' },
    { id: 'fibonacci', icon: Icon.fibonacci(16), label: 'Fibonacci', unlockFrom: 'M07' },
  ];
}
window.trendlineLabTools = trendlineLabTools;
