/* ===== Survey — conversational, chat-style, one question at a time ===== */

const STYLE_OPTIONS = [
  { id: 'cottage',     label: 'Cottage',     desc: 'Romantic, overflowing, full of color', color: '#D97757', accent: '#FDE68A' },
  { id: 'modern',      label: 'Modern',      desc: 'Clean lines, grasses, monochrome', color: '#3D4421', accent: '#E8E5DA' },
  { id: 'native',      label: 'Native PNW',  desc: 'Ferns, salal, evergreens — at home here', color: '#525B33', accent: '#B0BB7E' },
  { id: 'scandi',      label: 'Scandinavian', desc: 'Quiet, airy, pale grasses and gravel', color: '#78736A', accent: '#FAF9F6' },
  { id: 'farmhouse',   label: 'Farmhouse',   desc: 'Raised beds, lavender, gravel paths', color: '#9F4A30', accent: '#FEF3C7' },
  { id: 'coastal',     label: 'Coastal',     desc: 'Dune grasses, driftwood tones', color: '#3F6E73', accent: '#E0ECEE' },
];

const PROGRAM_OPTIONS = [
  { id: 'firepit',  icon: 'flame',     label: 'Fire pit' },
  { id: 'dining',   icon: 'utensils',  label: 'Outdoor dining' },
  { id: 'kids',     icon: 'toy-brick', label: 'Kids play' },
  { id: 'pets',     icon: 'dog',       label: 'Pet-friendly' },
  { id: 'cook',     icon: 'chef-hat',  label: 'Outdoor cooking' },
  { id: 'veg',      icon: 'carrot',    label: 'Raised beds for food' },
  { id: 'perennial', icon: 'flower-2', label: 'Perennial garden' },
  { id: 'curb',     icon: 'home',      label: 'Curb appeal' },
  { id: 'shade',    icon: 'tent-tree', label: 'Shade nook' },
];

const QUESTIONS = [
  {
    id: 'area', kind: 'options-grid',
    question: "First things first — what are we designing?",
    subtitle: "This sets the scope of your plan.",
    options: [
      { id: 'whole-new', label: 'Whole yard, from scratch', desc: 'Starting with bare ground or lawn' },
      { id: 'whole-refine', label: 'Whole yard, refine existing', desc: 'Rework what\'s already there' },
      { id: 'partial-new', label: 'Plant a new bed', desc: 'One area, designed thoroughly' },
      { id: 'partial-existing', label: 'Refine an existing bed', desc: 'Replant a bed you already have' },
    ],
  },
  {
    id: 'style', kind: 'style-cards',
    question: "What mood are you after?",
    subtitle: "Pick one or two. You can blend them.",
    multi: true,
  },
  {
    id: 'program', kind: 'chips',
    question: "How do you want to use the space?",
    subtitle: "Check anything that applies. We'll make room.",
    multi: true,
  },
  {
    id: 'lawn', kind: 'slider',
    question: "How much lawn?",
    subtitle: "Slide from 'no lawn' to 'all lawn'. Most people land somewhere playful.",
    labels: ['No lawn', 'A little', 'Half & half', 'Mostly lawn', 'All lawn'],
  },
  {
    id: 'maintenance', kind: 'options-grid',
    question: "How much maintenance are you up for?",
    subtitle: "Be honest — we've seen it all.",
    options: [
      { id: 'low', label: 'Low', desc: 'Weed-pull every few weeks. That\'s it.' },
      { id: 'med', label: 'Medium', desc: 'Happy to prune and deadhead on weekends.' },
      { id: 'high', label: 'High', desc: 'I want to fuss. Give me the roses.' },
    ],
  },
  {
    id: 'irrigation', kind: 'options-grid',
    question: "Would you install irrigation?",
    subtitle: "Drip lines save plants in zone 8b summers.",
    options: [
      { id: 'yes', label: 'Yes, whole yard', desc: 'Set it and forget it' },
      { id: 'some', label: 'In key areas', desc: 'Beds & new trees, not the lawn' },
      { id: 'no', label: 'No', desc: 'I\'ll hand-water' },
    ],
  },
];

const Survey = ({ onContinue }) => {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({
    style: ['modern', 'native'],
    program: ['firepit', 'dining', 'pets'],
    lawn: 2,
  });
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

  const current = QUESTIONS[step];
  const total = QUESTIONS.length;

  React.useEffect(() => {
    setTyping(true);
    const t = setTimeout(() => setTyping(false), 600);
    return () => clearTimeout(t);
  }, [step]);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [step, typing]);

  const next = () => {
    if (step < total - 1) setStep(s => s + 1);
    else onContinue(answers);
  };
  const set = (k, v) => setAnswers(a => ({ ...a, [k]: v }));
  const toggle = (k, v) => setAnswers(a => {
    const arr = a[k] || [];
    return { ...a, [k]: arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v] };
  });

  const canProgress = () => {
    const v = answers[current.id];
    if (current.multi) return v && v.length > 0;
    if (current.kind === 'slider') return true;
    return !!v;
  };

  return (
    <div className="screen screen-fade-in">
      <StepRail current="survey" />
      <div className="survey">
        <div className="survey__progress-bar">
          <div className="survey__progress-bar-fill" style={{ width: `${((step + 1) / total) * 100}%` }} />
        </div>

        <div className="survey__main">
          <div className="survey__chat" ref={scrollRef}>
            <div className="survey__bubble survey__bubble--assistant survey__bubble--intro">
              <div className="survey__avatar"><BlossomMark size={22} color="#FAF9F6" accent="#FDE68A" /></div>
              <div>
                <div className="survey__author">Novale · your design assistant</div>
                <div className="survey__msg">
                  Hi Emily 👋 — I've finished reading your site. A few quick questions and I'll draft your back yard. There are <strong>{total} questions</strong>; takes about 2 minutes.
                </div>
              </div>
            </div>

            {QUESTIONS.slice(0, step).map(q => (
              <React.Fragment key={q.id}>
                <AssistantBubble>{q.question}</AssistantBubble>
                <UserBubble>{formatAnswer(q, answers[q.id])}</UserBubble>
              </React.Fragment>
            ))}

            {typing ? (
              <div className="survey__bubble survey__bubble--assistant">
                <div className="survey__avatar"><BlossomMark size={22} color="#FAF9F6" accent="#FDE68A" /></div>
                <div className="survey__typing"><span /><span /><span /></div>
              </div>
            ) : (
              <>
                <AssistantBubble subtitle={current.subtitle}>{current.question}</AssistantBubble>
                <div className="survey__answer-area">
                  <AnswerWidget q={current} answers={answers} set={set} toggle={toggle} />
                </div>
              </>
            )}
          </div>

          <div className="survey__footer">
            <div className="muted" style={{ fontSize: 12 }}>
              Question <strong style={{ color: 'var(--fg-primary)' }}>{step + 1}</strong> of {total}
            </div>
            <div className="row" style={{ gap: 10 }}>
              {step > 0 && <button className="btn btn--ghost" onClick={() => setStep(s => s - 1)}><Icon name="arrow-left" size={14} /> Back</button>}
              <button className="btn btn--accent btn--lg" onClick={next} disabled={!canProgress()}>
                {step < total - 1 ? 'Next' : 'Generate my design'}
                <Icon name={step < total - 1 ? 'arrow-right' : 'sparkles'} size={16} />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const AssistantBubble = ({ children, subtitle }) => (
  <div className="survey__bubble survey__bubble--assistant">
    <div className="survey__avatar"><BlossomMark size={22} color="#FAF9F6" accent="#FDE68A" /></div>
    <div>
      <div className="survey__author">Novale</div>
      <div className="survey__msg">
        {children}
        {subtitle && <div className="survey__msg-sub">{subtitle}</div>}
      </div>
    </div>
  </div>
);
const UserBubble = ({ children }) => (
  <div className="survey__bubble survey__bubble--user">
    <div className="survey__msg">{children}</div>
  </div>
);

const formatAnswer = (q, v) => {
  if (q.kind === 'chips') {
    return (v || []).map(id => PROGRAM_OPTIONS.find(p => p.id === id)?.label).filter(Boolean).join(', ') || '—';
  }
  if (q.kind === 'style-cards') {
    return (v || []).map(id => STYLE_OPTIONS.find(s => s.id === id)?.label).filter(Boolean).join(' + ') || '—';
  }
  if (q.kind === 'options-grid') {
    return q.options.find(o => o.id === v)?.label || '—';
  }
  if (q.kind === 'slider') {
    return q.labels[v] || '—';
  }
  return String(v ?? '—');
};

const AnswerWidget = ({ q, answers, set, toggle }) => {
  if (q.kind === 'options-grid') {
    return (
      <div className="opts-grid" data-cols={q.options.length === 3 ? 3 : 2}>
        {q.options.map(o => (
          <button key={o.id} className="opt-card" data-selected={answers[q.id] === o.id} onClick={() => set(q.id, o.id)}>
            <div className="opt-card__label">{o.label}</div>
            <div className="opt-card__desc">{o.desc}</div>
            <div className="opt-card__check"><Icon name="check" size={12} stroke={3} /></div>
          </button>
        ))}
      </div>
    );
  }
  if (q.kind === 'style-cards') {
    const sel = answers[q.id] || [];
    return (
      <div className="style-grid">
        {STYLE_OPTIONS.map(s => (
          <button key={s.id} className="style-card" data-selected={sel.includes(s.id)} onClick={() => toggle(q.id, s.id)}>
            <StyleThumb style={s} />
            <div className="style-card__body">
              <div className="style-card__label">{s.label}</div>
              <div className="style-card__desc">{s.desc}</div>
            </div>
            <div className="style-card__check"><Icon name="check" size={12} stroke={3} /></div>
          </button>
        ))}
      </div>
    );
  }
  if (q.kind === 'chips') {
    const sel = answers[q.id] || [];
    return (
      <div className="chip-grid">
        {PROGRAM_OPTIONS.map(p => (
          <button key={p.id} className="chip" data-selected={sel.includes(p.id)} onClick={() => toggle(q.id, p.id)}>
            <Icon name={p.icon} size={16} />
            <span>{p.label}</span>
          </button>
        ))}
      </div>
    );
  }
  if (q.kind === 'slider') {
    const v = answers[q.id] ?? 2;
    return (
      <div className="lawn-slider">
        <div className="lawn-slider__track">
          {q.labels.map((l, i) => (
            <button key={i} className="lawn-slider__tick" data-selected={v === i} onClick={() => set(q.id, i)}>
              <div className="lawn-slider__dot" />
              <div className="lawn-slider__label">{l}</div>
            </button>
          ))}
        </div>
      </div>
    );
  }
  return null;
};

/* Illustrated style thumbnail */
const StyleThumb = ({ style }) => {
  const variants = {
    cottage: (
      <>
        <rect x="0" y="0" width="160" height="90" fill="#FEF3C7" />
        <circle cx="30" cy="60" r="16" fill="#D97757" opacity="0.7" />
        <circle cx="60" cy="72" r="10" fill="#D97757" />
        <circle cx="90" cy="65" r="14" fill="#9F4A30" opacity="0.7" />
        <circle cx="125" cy="74" r="12" fill="#D97757" opacity="0.8" />
        <path d="M0 82 Q 80 76 160 82 L 160 90 L 0 90 Z" fill="#6B7541" />
      </>
    ),
    modern: (
      <>
        <rect x="0" y="0" width="160" height="90" fill="#FAF9F6" />
        <rect x="15" y="40" width="40" height="42" fill="#3D4421" opacity="0.85" />
        <rect x="60" y="55" width="30" height="27" fill="#78736A" />
        {Array.from({length: 6}).map((_, i) => <line key={i} x1={100 + i*8} y1="55" x2={96 + i*8} y2="82" stroke="#3D4421" strokeWidth="1.2" />)}
      </>
    ),
    native: (
      <>
        <rect x="0" y="0" width="160" height="90" fill="#F5F6EE" />
        <path d="M20 82 L 15 55 L 20 30 L 25 55 Z" fill="#3D4421" />
        <path d="M50 82 L 42 50 L 50 20 L 58 50 Z" fill="#2D331A" />
        <path d="M80 82 L 73 58 L 80 35 L 87 58 Z" fill="#525B33" />
        <circle cx="120" cy="65" r="18" fill="#3D4421" opacity="0.6" />
        <circle cx="140" cy="72" r="10" fill="#6B7541" />
      </>
    ),
    scandi: (
      <>
        <rect x="0" y="0" width="160" height="90" fill="#FAF9F6" />
        <rect x="0" y="72" width="160" height="18" fill="#E8E5DA" />
        {Array.from({length: 8}).map((_, i) => (
          <g key={i}>
            <line x1={14 + i*18} y1="70" x2={12 + i*18} y2="40" stroke="#A8A294" strokeWidth="1" />
            <line x1={14 + i*18} y1="70" x2={17 + i*18} y2="42" stroke="#A8A294" strokeWidth="1" />
          </g>
        ))}
      </>
    ),
    farmhouse: (
      <>
        <rect x="0" y="0" width="160" height="90" fill="#FEF3C7" />
        <rect x="10" y="50" width="40" height="30" fill="#7C5A3A" />
        <rect x="60" y="55" width="40" height="25" fill="#9F4A30" opacity="0.85" />
        <rect x="110" y="50" width="40" height="30" fill="#7C5A3A" />
        {/* lavender */}
        {Array.from({length: 9}).map((_, i) => (
          <line key={i} x1={15 + i*16} y1="50" x2={15 + i*16} y2="40" stroke="#9F4A30" strokeWidth="1.5" />
        ))}
      </>
    ),
    coastal: (
      <>
        <rect x="0" y="0" width="160" height="90" fill="#E0ECEE" />
        <rect x="0" y="72" width="160" height="18" fill="#D6D2C2" />
        {Array.from({length: 12}).map((_, i) => (
          <g key={i}>
            <line x1={10 + i*12} y1="72" x2={8 + i*12} y2="48" stroke="#78736A" strokeWidth="1" />
            <line x1={10 + i*12} y1="72" x2={13 + i*12} y2="50" stroke="#78736A" strokeWidth="1" />
          </g>
        ))}
      </>
    ),
  };
  return (
    <svg className="style-card__thumb" viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice">
      {variants[style.id]}
    </svg>
  );
};

Object.assign(window, { Survey });
