/* ============================================================
   AI Roadmap Quiz — Main App Component
   Loads as type="text/babel". Reads from window.QUIZ.
   ============================================================ */

const { useState, useEffect, useMemo, useRef } = React;
const Q = window.QUIZ;

/* ---------- ICONS (lucide-style, stroke-based) ---------- */
const Icon = ({ name, size = 20, ...props }) => {
  const s = { stroke: "currentColor", strokeWidth: 1.75, strokeLinecap: "round", strokeLinejoin: "round", fill: "none" };
  const paths = {
    arrow: <><path d="M5 12h14"/><path d="m13 5 7 7-7 7"/></>,
    back: <><path d="M19 12H5"/><path d="m11 19-7-7 7-7"/></>,
  };
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} {...s} {...props}>
      {paths[name]}
    </svg>
  );
};

/* ---------- SPLASH SCREEN ---------- */
const SplashScreen = ({ onStart }) => (
  <div className="qz-splash qz-fade-in">
    <div className="qz-splash-inner">
      <img src="design/assets/logo-fiftyminds.png" alt="fiftyminds" className="qz-splash-logo"/>
      <h1 className="qz-splash-title">Intro to AI<br/>Discovery Questions</h1>
      <p className="qz-splash-lead">This helps us understand your organisation's current AI setup and future plans.</p>
      <button className="qz-btn qz-btn-primary qz-splash-cta" onClick={onStart}>
        Begin <Icon name="arrow" size={18} className="qz-arrow"/>
      </button>
    </div>
  </div>
);

/* ---------- DETAILS SCREEN ---------- */
const DetailsScreen = ({ values, onChange, onNext, onBack, stepNum, stepTotal }) => {
  const valid = !!values.employees;
  return (
    <div className="qz-stage qz-fade-in">
      <div className="qz-stage-inner">
        <Progress current={stepNum} total={stepTotal} sectionLabel="About the organisation" />
        <h2 className="qz-question">How many people are in the organisation?</h2>
        <div className="qz-form">
          <div className="qz-field">
            <label className="qz-label">Number of employees</label>
            <select className="qz-select" value={values.employees || ""} onChange={e => onChange({ ...values, employees: e.target.value })}>
              <option value="">Select…</option>
              {Q.EMPLOYEE_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
            </select>
          </div>
        </div>
        <div className="qz-nav">
          <button className="qz-btn qz-btn-ghost" onClick={onBack}><Icon name="back" size={16}/> Back</button>
          <button className="qz-btn qz-btn-primary" disabled={!valid} onClick={onNext}>
            Continue <Icon name="arrow" size={16} className="qz-arrow"/>
          </button>
        </div>
      </div>
    </div>
  );
};

/* ---------- QUESTION SCREEN ---------- */
const QuestionScreen = ({ q, qIndex, total, value, onChange, onNext, onBack, stepNum, stepTotal }) => {
  if (q.multiSelect) {
    const sel = (value && value.selected) ? value.selected : [];
    const otherText = (value && value.other != null) ? value.other : '';
    const noneIdx = q.options.findIndex(o => o.exclusive);

    const toggle = (i) => {
      if (q.options[i].exclusive) {
        onChange({ selected: sel.includes(i) ? [] : [i], other: '' });
      } else {
        const newSel = sel.includes(i)
          ? sel.filter(s => s !== i)
          : [...sel.filter(s => s !== noneIdx), i];
        onChange({ selected: newSel, other: otherText });
      }
    };

    const setOther = (text) => {
      onChange({ selected: sel.filter(s => s !== noneIdx), other: text });
    };

    const valid = sel.length > 0 || otherText.trim().length > 0;

    return (
      <div className="qz-stage qz-fade-in" key={q.id}>
        <div className="qz-stage-inner">
          <Progress current={stepNum} total={stepTotal} sectionLabel={q.section} />
          <h2 className="qz-question">{q.question}</h2>
          <div className="qz-options">
            {q.options.map((opt, i) => (
              <button key={i} className={`qz-option ${sel.includes(i) ? 'selected' : ''}`} onClick={() => toggle(i)}>
                <span className="qz-checkbox">{sel.includes(i) && (
                  <svg viewBox="0 0 14 14" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 7l3.5 3.5 6-6"/></svg>
                )}</span>
                <span>{opt.label}</span>
              </button>
            ))}
            {q.hasOther && (
              <div className={`qz-option qz-option-other ${otherText.trim() ? 'selected' : ''}`}>
                <span className="qz-checkbox">{otherText.trim() && (
                  <svg viewBox="0 0 14 14" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 7l3.5 3.5 6-6"/></svg>
                )}</span>
                <input
                  className="qz-other-input"
                  type="text"
                  placeholder="Other AI tools - please list"
                  value={otherText}
                  onChange={e => setOther(e.target.value)}
                />
              </div>
            )}
          </div>
          <div className="qz-nav">
            <button className="qz-btn qz-btn-ghost" onClick={onBack}><Icon name="back" size={16}/> Back</button>
            <button className="qz-btn qz-btn-primary" disabled={!valid} onClick={onNext}>
              Continue <Icon name="arrow" size={16} className="qz-arrow"/>
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (q.freeText) {
    return (
      <div className="qz-stage qz-fade-in" key={q.id}>
        <div className="qz-stage-inner">
          <Progress current={stepNum} total={stepTotal} sectionLabel={q.section} />
          <h2 className="qz-question">{q.question}</h2>
          <textarea
            className="qz-textarea"
            placeholder="Share anything that would help us prepare"
            value={value || ''}
            onChange={e => onChange(e.target.value)}
            rows={6}
          />
          <div className="qz-nav">
            <button className="qz-btn qz-btn-ghost" onClick={onBack}><Icon name="back" size={16}/> Back</button>
            <button className="qz-btn qz-btn-primary" onClick={onNext}>
              Submit <Icon name="arrow" size={16} className="qz-arrow"/>
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="qz-stage qz-fade-in" key={q.id}>
      <div className="qz-stage-inner">
        <Progress current={stepNum} total={stepTotal} sectionLabel={q.section} />
        <h2 className="qz-question">{q.question}</h2>
        <div className="qz-options">
          {q.options.map((opt, i) => (
            <button
              key={i}
              className={`qz-option ${value === i ? 'selected' : ''}`}
              onClick={() => onChange(i)}
            >
              <span className="qz-radio"/>
              <span>{opt.label}</span>
            </button>
          ))}
        </div>
        <div className="qz-nav">
          <button className="qz-btn qz-btn-ghost" onClick={onBack}><Icon name="back" size={16}/> Back</button>
          <button className="qz-btn qz-btn-primary" disabled={value === undefined || value === null} onClick={onNext}>
            Continue <Icon name="arrow" size={16} className="qz-arrow"/>
          </button>
        </div>
      </div>
    </div>
  );
};

/* ---------- ATTENDEES SCREEN ---------- */
const AttendeesScreen = ({ values, onChange, onNext, stepNum, stepTotal }) => {
  const extra = values.attendees && values.attendees.length ? values.attendees : [];

  const updateExtra = (i, field, val) => {
    const updated = extra.map((a, idx) => idx === i ? { ...a, [field]: val } : a);
    onChange({ ...values, attendees: updated });
  };

  const addExtra = () => {
    onChange({ ...values, attendees: [...extra, { name: '', role: '' }] });
  };

  const removeExtra = (i) => {
    onChange({ ...values, attendees: extra.filter((_, idx) => idx !== i) });
  };

  const valid = values.company && values.name && values.role
    && values.email && /\S+@\S+\.\S+/.test(values.email);

  return (
    <div className="qz-stage qz-fade-in">
      <div className="qz-stage-inner">
        <Progress current={stepNum} total={stepTotal} sectionLabel="About your session" />
        <h2 className="qz-question">Who will be in attendance?</h2>
        <div className="qz-form">
          <div className="qz-field">
            <label className="qz-label">Company name</label>
            <input className="qz-input" type="text" value={values.company || ""} onChange={e => onChange({ ...values, company: e.target.value })}/>
          </div>
          <div className="qz-row">
            <div className="qz-field">
              <label className="qz-label">Your name</label>
              <input className="qz-input" type="text" value={values.name || ""} onChange={e => onChange({ ...values, name: e.target.value })}/>
            </div>
            <div className="qz-field">
              <label className="qz-label">Your role</label>
              <input className="qz-input" type="text" value={values.role || ""} onChange={e => onChange({ ...values, role: e.target.value })}/>
            </div>
          </div>
          <div className="qz-field">
            <label className="qz-label">Your email</label>
            <input className="qz-input" type="email" value={values.email || ""} onChange={e => onChange({ ...values, email: e.target.value })}/>
          </div>
          {extra.length > 0 && (
            <div className="qz-field">
              <label className="qz-label">Additional attendees</label>
              {extra.map((att, i) => (
                <div key={i} className="qz-attendee-row">
                  <input className="qz-input" type="text" placeholder="Full name" value={att.name} onChange={e => updateExtra(i, 'name', e.target.value)}/>
                  <input className="qz-input" type="text" placeholder="Role / job title" value={att.role} onChange={e => updateExtra(i, 'role', e.target.value)}/>
                  <button className="qz-attendee-remove" type="button" onClick={() => removeExtra(i)} aria-label="Remove attendee">×</button>
                </div>
              ))}
            </div>
          )}
          <button className="qz-btn qz-btn-ghost qz-attendee-add" type="button" onClick={addExtra}>
            + Add another attendee
          </button>
        </div>
        <div className="qz-nav">
          <button className="qz-btn qz-btn-primary" disabled={!valid} onClick={onNext}>
            Continue <Icon name="arrow" size={16} className="qz-arrow"/>
          </button>
        </div>
      </div>
    </div>
  );
};

/* ---------- PROGRESS BAR ---------- */
const Progress = ({ current, total, sectionLabel }) => {
  const pct = Math.max(0.04, current / total);
  return (
    <div className="qz-progress">
      <div className="qz-progress-bar">
        <div className="qz-progress-fill" style={{transform: `scaleX(${pct})`}}/>
      </div>
    </div>
  );
};

/* ---------- THANK YOU SCREEN ---------- */
const ThankYouScreen = () => (
  <div className="qz-thankyou qz-fade-in">
    <div className="qz-thankyou-inner">
      <img src="design/assets/logo-fiftyminds.png" alt="fiftyminds" className="qz-splash-logo"/>
      <h1 className="qz-thankyou-title">Thank you.</h1>
      <p className="qz-thankyou-lead">We look forward to your session.</p>
    </div>
  </div>
);

/* ============================================================
   MAIN APP
   ============================================================ */

/* ============================================================
   EMAILJS — fill in your credentials from emailjs.com
   ============================================================ */
const EMAILJS_PUBLIC_KEY  = "a_7LCV9VwTbMa971Y";
const EMAILJS_SERVICE_ID  = "service_u6rd5qd";
const EMAILJS_TEMPLATE_ID = "template_a2i9djb";

const sendResults = (contact, details, answers) => {
  const toolsAns = answers["q_tools"] || {};
  const toolsSelected = (toolsAns.selected || [])
    .map(i => Q.Q_TOOLS.options[i]?.label).filter(Boolean).join(", ") || "—";
  const toolsOther = toolsAns.other ? `Other: ${toolsAns.other}` : "";
  const toolsFull = [toolsSelected, toolsOther].filter(Boolean).join(", ");

  const getLabel = (q, idx) =>
    (idx !== undefined && idx !== null) ? (q.options[idx]?.label || "—") : "—";

  const attendeeList = (contact.attendees || []).length > 0
    ? contact.attendees.map(a => `${a.name} (${a.role})`).join(", ")
    : "None";

  emailjs.send(EMAILJS_SERVICE_ID, EMAILJS_TEMPLATE_ID, {
    company:       contact.company  || "—",
    name:          contact.name     || "—",
    role:          contact.role     || "—",
    email:         contact.email    || "—",
    attendees:     attendeeList,
    employees:     details.employees || "—",
    tools:         toolsFull || "None",
    q1_depth:      getLabel(Q.Q1, answers[Q.Q1.id]),
    q2_strategy:   getLabel(Q.Q2, answers[Q.Q2.id]),
    q3_data:       getLabel(Q.Q3, answers[Q.Q3.id]),
    q4_governance: getLabel(Q.Q4, answers[Q.Q4.id]),
    q5_process:    getLabel(Q.Q5, answers[Q.Q5.id]),
    q6_team:       getLabel(Q.Q6, answers[Q.Q6.id]),
    q8_challenge:  getLabel(Q.Q8, answers[Q.Q8.id]),
    q_final:       answers["q_final"] || "—",
  }, EMAILJS_PUBLIC_KEY).catch(err => console.error("EmailJS error:", err));
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light"
}/*EDITMODE-END*/;

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [phase, setPhase] = useState("splash"); // splash | contact | details | question | thankyou
  const [qIdx, setQIdx] = useState(0);
  const [details, setDetails] = useState({});
  const [answers, setAnswers] = useState({});
  const [contact, setContact] = useState({});

  // total step count: attendees(1) + details(2) + 9 questions(3-11) = 11
  const stepTotal = 11;
  const currentStep = useMemo(() => {
    if (phase === "contact") return 1;
    if (phase === "details") return 2;
    if (phase === "question") return 3 + qIdx;
    return stepTotal;
  }, [phase, qIdx]);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [phase, qIdx]);

  const advance = () => {
    if (qIdx + 1 < Q.QUESTIONS.length) {
      setQIdx(qIdx + 1);
    } else {
      sendResults(contact, details, answers);
      setPhase("thankyou");
    }
  };

  const goBack = () => {
    if (phase === "details") setPhase("contact");
    else if (phase === "question") {
      if (qIdx === 0) setPhase("details");
      else setQIdx(qIdx - 1);
    }
  };

  const theme = tweaks.theme || "light";

  return (
    <div className="quiz-shell" data-theme={theme}>
      {phase === "splash" && <SplashScreen onStart={() => setPhase("contact")}/>}
      {phase === "contact" && (
        <AttendeesScreen
          values={contact}
          onChange={setContact}
          onNext={() => setPhase("details")}
          stepNum={1}
          stepTotal={stepTotal}
        />
      )}
      {phase === "details" && (
        <DetailsScreen
          values={details}
          onChange={setDetails}
          onNext={() => { setQIdx(0); setPhase("question"); }}
          onBack={goBack}
          stepNum={currentStep}
          stepTotal={stepTotal}
        />
      )}
      {phase === "question" && (
        <QuestionScreen
          q={Q.QUESTIONS[qIdx]}
          qIndex={qIdx}
          total={Q.QUESTIONS.length}
          value={answers[Q.QUESTIONS[qIdx].id]}
          onChange={(val) => setAnswers(prev => ({ ...prev, [Q.QUESTIONS[qIdx].id]: val }))}
          onNext={advance}
          onBack={goBack}
          stepNum={currentStep}
          stepTotal={stepTotal}
        />
      )}
      {phase === "thankyou" && <ThankYouScreen/>}

      {/* Tweaks Panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Visual style">
          <TweakRadio
            label="Theme"
            value={tweaks.theme}
            onChange={v => setTweak('theme', v)}
            options={[
              { value: "light", label: "Light" },
              { value: "dark", label: "Dark" },
              { value: "cardstack", label: "Cards" },
            ]}
          />
        </TweakSection>
        <TweakSection label="Jump to">
          <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
            <button className="tw-btn" onClick={() => setPhase("splash")}>Splash</button>
            <button className="tw-btn" onClick={() => setPhase("contact")}>Attendees</button>
            <button className="tw-btn" onClick={() => setPhase("details")}>Details</button>
            <button className="tw-btn" onClick={() => { setQIdx(0); setPhase("question"); }}>Q1</button>
            <button className="tw-btn" onClick={() => setPhase("thankyou")}>Thank you</button>
          </div>
          <style>{`
            .tw-btn {
              padding: 6px 12px; font-size: 12px; border-radius: 6px;
              border: 1px solid rgba(255,255,255,0.18); background: transparent;
              color: inherit; cursor: pointer; font-family: var(--font-body);
            }
            .tw-btn:hover { background: rgba(255,255,255,0.06); }
          `}</style>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
