/* global React, VoiceQuestionCard, Segmented, TextArea, FieldLabel, PrimaryButton, GhostLink, SubProgress, PAOS */
const { useState, useEffect, useMemo } = React;

// ─────────────────────────────────────────────────────────────
// Resolve a step's visible question list against form data
// (handles conditional questions like 3.6)
// ─────────────────────────────────────────────────────────────
function resolveQuestions(questions, formData) {
  return questions.filter(q => {
    if (!q.conditional) return true;
    const { dependsOn, equals } = q.conditional;
    return formData?.[dependsOn] === equals;
  });
}

// ─────────────────────────────────────────────────────────────
// Generic voice step — one question per screen
// ─────────────────────────────────────────────────────────────
function VoiceStep({ stepConfig, subStep, setSubStep, t, onNext, answers, setAnswers, step2Data }) {
  const visibleQs = useMemo(
    () => resolveQuestions(stepConfig.questions, step2Data),
    [stepConfig, step2Data]
  );
  // Clamp subStep
  const idx = Math.min(subStep, visibleQs.length - 1);
  const q = visibleQs[idx];

  const isFirst = idx === 0;
  const isLast = idx === visibleQs.length - 1;

  const v = answers[q.id];
  const setV = (val) => setAnswers({ ...answers, [q.id]: val });

  const hasInput = (() => {
    if (!v) return false;
    if (q.kind === 'asset') return !!v?.text?.trim();
    if (q.kind === 'scale') return v?.scale != null;
    if (q.kind === 'final') return v?.ready != null;
    return !!v?.text?.trim() || !!v?.audio;
  })();

  const handleNext = () => {
    if (!isLast) setSubStep(idx + 1);
    else onNext();
  };
  const skip = () => {
    if (!isLast) setSubStep(idx + 1);
    else onNext();
  };

  return (
    <div style={{
      padding: '0 24px 24px',
      display: 'flex', flexDirection: 'column', gap: 18,
      minHeight: '100%',
    }}>
      {/* step caption */}
      <div>
        <div style={{
          fontFamily: 'Geist Mono, monospace', fontSize: 10,
          letterSpacing: '0.12em', textTransform: 'uppercase', color: t.primary,
          marginBottom: 6,
        }}>
          {stepConfig.title}
        </div>
        {isFirst && stepConfig.subtitle && (
          <div style={{
            fontFamily: 'Geist, system-ui, sans-serif', fontSize: 13,
            color: t.inkSoft, lineHeight: 1.5, marginBottom: 4,
          }}>
            {stepConfig.subtitle}
          </div>
        )}
      </div>

      {/* sub-progress */}
      <SubProgress index={idx} total={visibleQs.length} t={t} />

      {/* the question (animated swap) */}
      <div key={q.id} style={{ animation: 'fadeUp 380ms ease both', flex: 1 }}>
        <QuestionRenderer q={q} value={v} onChange={setV} t={t} />
      </div>

      {/* footer */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 }}>
        <PrimaryButton t={t} onClick={handleNext} disabled={!hasInput}>
          {isLast ? (q.kind === 'final' ? 'Finish' : 'Continue →') : 'Next question →'}
        </PrimaryButton>
        {!hasInput && q.kind !== 'final' && (
          <div style={{
            textAlign: 'center',
            fontFamily: 'Geist, system-ui, sans-serif',
            fontSize: 12, color: t.inkFaint,
          }}>
            Record an answer, or type “N/A” if it doesn’t apply.
          </div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// QuestionRenderer — picks input style based on q.kind
// ─────────────────────────────────────────────────────────────
function QuestionRenderer({ q, value, onChange, t }) {
  if (q.kind === 'asset') return <AssetQuestion q={q} value={value} onChange={onChange} t={t} />;
  if (q.kind === 'scale') return <ScaleQuestion q={q} value={value} onChange={onChange} t={t} />;
  if (q.kind === 'final') return <FinalQuestion q={q} value={value} onChange={onChange} t={t} />;
  return <VoiceQuestionCard question={q} value={value} onChange={onChange} t={t} />;
}

// Paragraph-text-only question (no voice memo)
function AssetQuestion({ q, value, onChange, t }) {
  const v = value || { text: '' };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginBottom: 6 }}>
          <span style={{
            fontFamily: 'Geist Mono, monospace', fontSize: 10,
            color: t.primary, fontWeight: 500,
          }}>{q.id}</span>
          {q.label && (
            <span style={{
              fontFamily: 'Geist Mono, monospace', fontSize: 10,
              color: t.inkFaint, letterSpacing: '0.05em',
              textTransform: 'uppercase',
            }}>· {q.label}</span>
          )}
          <span style={{
            marginLeft: 'auto',
            fontFamily: 'Geist Mono, monospace', fontSize: 10,
            color: t.inkFaint, padding: '3px 8px', borderRadius: 100,
            border: `1px solid ${t.line}`,
          }}>Links / text</span>
        </div>
        <h2 style={{
          fontFamily: '"Instrument Serif", Georgia, serif',
          fontSize: 26, lineHeight: 1.12, margin: 0, color: t.ink,
          letterSpacing: '-0.01em', fontWeight: 400, textWrap: 'pretty',
        }}>{q.q}</h2>
        {q.hint && (
          <div style={{
            fontFamily: 'Geist, system-ui, sans-serif',
            fontSize: 13, color: t.inkSoft, marginTop: 8, lineHeight: 1.5,
          }}>{q.hint}</div>
        )}
      </div>
      <TextArea
        value={v.text} onChange={(text) => onChange({ text })}
        placeholder="Paste links, one per line — or write a short note." t={t} rows={6}
      />
    </div>
  );
}

// 1-10 scale question
function ScaleQuestion({ q, value, onChange, t }) {
  const v = value || {};
  const choose = (n) => onChange({ ...v, scale: n });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginBottom: 6 }}>
          <span style={{
            fontFamily: 'Geist Mono, monospace', fontSize: 10,
            color: t.primary, fontWeight: 500,
          }}>{q.id}</span>
          <span style={{
            fontFamily: 'Geist Mono, monospace', fontSize: 10,
            color: t.inkFaint, letterSpacing: '0.05em',
            textTransform: 'uppercase',
          }}>· {q.label}</span>
        </div>
        <h2 style={{
          fontFamily: '"Instrument Serif", Georgia, serif',
          fontSize: 26, lineHeight: 1.12, margin: 0, color: t.ink,
          letterSpacing: '-0.01em', fontWeight: 400, textWrap: 'pretty',
        }}>{q.q}</h2>
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: 4,
      }}>
        {Array.from({ length: 10 }, (_, i) => i + 1).map(n => {
          const on = v.scale === n;
          return (
            <button
              key={n}
              onClick={() => choose(n)}
              style={{
                aspectRatio: '1', borderRadius: 10,
                border: `1.5px solid ${on ? t.primary : t.line}`,
                background: on ? t.primary : t.surface,
                color: on ? '#fff' : t.ink,
                fontFamily: 'Geist Mono, monospace', fontSize: 13,
                fontWeight: 600, cursor: 'pointer',
                transition: 'all 160ms',
              }}
            >{n}</button>
          );
        })}
      </div>
      <div style={{
        display: 'flex', justifyContent: 'space-between',
        fontFamily: 'Geist, system-ui, sans-serif', fontSize: 12,
        color: t.inkSoft,
      }}>
        <span>Not really</span>
        <span>Completely</span>
      </div>
    </div>
  );
}

// Final ready / not ready
function FinalQuestion({ q, value, onChange, t }) {
  const v = value || {};
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      gap: 18, paddingTop: 24, textAlign: 'center',
    }}>
      <div style={{
        fontFamily: 'Geist Mono, monospace', fontSize: 10,
        color: t.primary, fontWeight: 500, letterSpacing: '0.1em',
      }}>{q.id} · LAST ONE</div>
      <h2 style={{
        fontFamily: '"Instrument Serif", Georgia, serif',
        fontSize: 38, lineHeight: 1.05, margin: 0, color: t.ink,
        letterSpacing: '-0.02em', fontWeight: 400, textWrap: 'balance',
        maxWidth: 280,
      }}>{q.q}</h2>
      <div style={{
        fontFamily: 'Geist, system-ui, sans-serif', fontSize: 14,
        color: t.inkSoft, maxWidth: 280, lineHeight: 1.5,
      }}>
        Saying yes locks in your slot and unlocks the kick-off plan.
      </div>
      <div style={{
        display: 'flex', gap: 12, marginTop: 6, width: '100%',
        alignItems: 'center', justifyContent: 'center',
      }}>
        <button
          onClick={() => onChange({ ...v, ready: false })}
          style={{
            width: 80, height: 52, borderRadius: 26,
            border: `1.5px solid ${v.ready === false ? t.primary : t.line}`,
            background: v.ready === false ? t.primary : t.surface,
            color: v.ready === false ? '#fff' : t.inkSoft,
            fontFamily: 'Geist, system-ui, sans-serif', fontSize: 14,
            fontWeight: 600, cursor: 'pointer',
            transition: 'all 160ms',
          }}
        >Not yet</button>
        <button
          onClick={() => onChange({ ...v, ready: true })}
          style={{
            position: 'relative', width: 140, height: 64, borderRadius: 32,
            border: 'none', cursor: 'pointer',
            background: t.primary, color: '#fff',
            fontFamily: 'Geist, system-ui, sans-serif', fontSize: 17,
            fontWeight: 700, letterSpacing: '-0.01em',
            boxShadow: `0 0 0 ${v.ready === true ? 8 : 0}px ${t.primary}22, 0 12px 32px ${t.primary}55`,
            transition: 'all 200ms',
            animation: v.ready !== true ? `glow 2.4s ease-in-out infinite` : 'none',
          }}
        >
          Yes, I'm in
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { VoiceStep, resolveQuestions });
