// Main onboarding app — orchestrates the state machine, layout, transitions.
//
// Adapted from the design bundle's cc-onboarding.jsx. Two changes from the
// design's prototype:
//   1. TweaksPanel removed — it's a design-time tool, not a customer feature.
//      Accent palette is hardcoded to the Ecosystem blue→purple direction.
//   2. Summary recommendation rewritten to map answers onto the 10-plan
//      catalog (5 segments x Basic/Pro) used by the production /pricing page.
//      The "See plans" CTA navigates to /pricing?plan=<slug>.

const { useState, useEffect, useMemo, useRef } = React;

// Inlined from cc-tweaks (which we don't ship): used by the brand panel +
// summary card to pick palette colors.
const ACCENT_OPTIONS = {
  blue: { color: '#4ea6ff', accent: '#8a5cf6', label: 'Ecosystem (blue → purple)' },
};

// Plan catalog mirror — must stay in sync with the seeds in
// migrations/037_billing_restructure.sql. Kept in JS (rather than fetched)
// so the questionnaire page is fully static — no API dependency, no flash
// of unstyled content.
const PLAN_TABLE = {
  small_shop_basic:     { slug:'small_shop_basic',     name:'Small Shop · Basic',     monthly_price:'$30/mo',  blurb:'1–4 employees, 1–2 bays. Booking, invoicing, customer records.' },
  small_shop_pro:       { slug:'small_shop_pro',       name:'Small Shop · Pro',       monthly_price:'$50/mo',  blurb:'Adds SMS, advanced reports, an extra user, 100 emails/mo.' },
  medium_shop_basic:    { slug:'medium_shop_basic',    name:'Medium Shop · Basic',    monthly_price:'$60/mo',  blurb:'Up to 20 employees. Booking, invoicing, bay scheduling.' },
  medium_shop_pro:      { slug:'medium_shop_pro',      name:'Medium Shop · Pro',      monthly_price:'$80/mo',  blurb:'Adds SMS, advanced reports, an extra user, 100 emails/mo.' },
  large_shop_basic:     { slug:'large_shop_basic',     name:'Large Shop · Basic',     monthly_price:'$120/mo', blurb:'20+ employees, multi-location. Unlimited users, bay scheduling.' },
  large_shop_pro:       { slug:'large_shop_pro',       name:'Large Shop · Pro',       monthly_price:'$140/mo', blurb:'Adds SMS, advanced reports, 100 emails/mo.' },
  mobile_detailer_basic:{ slug:'mobile_detailer_basic',name:'Mobile Detailer · Basic',monthly_price:'$30/mo',  blurb:'Solo detailer. Booking, travel estimates, on-site invoicing.' },
  mobile_detailer_pro:  { slug:'mobile_detailer_pro',  name:'Mobile Detailer · Pro',  monthly_price:'$50/mo',  blurb:'Adds SMS, advanced reports, an extra user, 100 emails/mo.' },
  mobile_fleet_basic:   { slug:'mobile_fleet_basic',   name:'Mobile Fleet · Basic',   monthly_price:'$60/mo',  blurb:'Multiple mobile techs, shared schedule, on-site invoicing.' },
  mobile_fleet_pro:     { slug:'mobile_fleet_pro',     name:'Mobile Fleet · Pro',     monthly_price:'$80/mo',  blurb:'Adds SMS, advanced reports, an extra user, 100 emails/mo.' },
};

// (op, size, volume, goal) → one of the 10 plan slugs.
// volume thresholds bump a "cheaper / starting" answer up to Pro when the
// throughput would otherwise outgrow Basic's quotas.
function recommendPlan({ op, size, volume, goal }) {
  let segment;
  if (op === 'mobile') {
    segment = size === 'fleet' ? 'mobile_fleet' : 'mobile_detailer';
  } else if (size === 'large') {
    segment = 'large_shop';
  } else if (size === 'medium') {
    segment = 'medium_shop';
  } else {
    segment = 'small_shop';
  }

  let tier = (goal === 'scale' || goal === 'better') ? 'pro' : 'basic';
  const volumeBump = {
    small_shop:      60,
    mobile_detailer: 60,
    medium_shop:    120,
    mobile_fleet:   120,
    large_shop:     200,
  }[segment];
  if (typeof volume === 'number' && volume >= volumeBump) tier = 'pro';

  return PLAN_TABLE[`${segment}_${tier}`];
}

// Compute dynamic flow based on op type
const buildFlow = (answers) => {
  const steps = [
    { id: 'start',  label: 'Starting point',                                              short: 'Start',  n: 1 },
    { id: 'op',     label: 'Operation type',                                              short: 'Type',   n: 2 },
    { id: 'size',   label: answers.op === 'mobile' ? 'Crew size' : 'Shop size',           short: 'Size',   n: 3 },
    { id: 'volume', label: 'Weekly volume',                                               short: 'Volume', n: 4 },
    { id: 'goal',   label: 'Your goal',                                                   short: 'Goal',   n: 5 },
    { id: 'square', label: 'Payments',                                                    short: 'Square', n: 6 },
  ];
  return steps;
};

// Map answer keys to nice readable labels (recap card).
const READABLE = {
  start: { replace: 'Switching from another tool', fresh: 'Starting fresh' },
  op:    { mobile: 'Mobile detailing', shop: 'Brick & mortar shop' },
  size:  {
    small:  'Small shop · 1–4 employees, 1–2 bays',
    medium: 'Medium shop · up to 20 employees, ~10 bays',
    large:  'Large / multi-location · 20+ employees',
    solo:   'Solo detailer',
    fleet:  'Fleet — multiple detailers',
  },
  goal:  {
    better:   'Better software',
    scale:    'Software that scales',
    cheaper:  'Cheaper option',
    starting: 'Just getting started',
  },
  square: { has: 'Existing Square account', need: 'Will set one up', later: 'Decide later' },
};

// ─── Left brand panel ───────────────────────────────────────────
const BrandPanel = ({ activeIdx, steps, palette }) => (
  <div style={{
    width: 320, flexShrink: 0,
    background: '#0b1220',
    color: '#ffffff',
    padding: '40px 36px',
    display: 'flex', flexDirection: 'column',
    position: 'sticky', top: 0, height: '100vh',
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 48 }}>
      <EcoConstellation size={42} color={palette.color} accent={palette.accent} />
      <CCWordmark size={22} color="#ffffff" accent={palette.color} />
    </div>

    <div style={{ marginBottom: 36 }}>
      <div className="caption" style={{ color: 'rgba(255,255,255,0.45)', marginBottom: 12 }}>Getting started</div>
      <h2 style={{
        margin: 0, fontSize: 24, lineHeight: 1.18, letterSpacing: '-0.018em', fontWeight: 500,
        color: '#ffffff',
      }}>
        Let's find your plan.
      </h2>
      <p style={{ margin: '10px 0 0', fontSize: 13.5, lineHeight: 1.55, color: 'rgba(255,255,255,0.55)' }}>
        Six quick questions. Most folks finish in under two minutes.
      </p>
    </div>

    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      {steps.map((s, i) => {
        const isActive = i === activeIdx;
        const isDone = i < activeIdx;
        return (
          <div key={s.id} style={{
            display: 'flex', alignItems: 'center', gap: 14,
            padding: '10px 0', opacity: isActive || isDone ? 1 : 0.55,
            transition: 'opacity .2s ease',
          }}>
            <div style={{
              width: 24, height: 24, borderRadius: '50%',
              border: '1.5px solid ' + (isActive ? palette.color : (isDone ? palette.color : 'rgba(255,255,255,0.22)')),
              background: isDone ? palette.color : (isActive ? 'transparent' : 'transparent'),
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              transition: 'all .2s ease',
            }}>
              {isDone ? (
                <svg width="11" height="11" viewBox="0 0 12 12"><path d="M2.5 6.2 L5 8.5 L9.5 3.5" stroke="#0b1220" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
              ) : (
                <span className="mono" style={{ fontSize: 10.5, color: isActive ? palette.color : 'rgba(255,255,255,0.45)' }}>{String(s.n).padStart(2, '0')}</span>
              )}
            </div>
            <div style={{
              fontSize: 14, color: isActive ? '#ffffff' : (isDone ? 'rgba(255,255,255,0.7)' : 'rgba(255,255,255,0.55)'),
              fontWeight: isActive ? 500 : 400,
            }}>{s.label}</div>
          </div>
        );
      })}
    </div>

    <div style={{ flex: 1 }} />

    <div style={{ borderTop: '1px solid rgba(255,255,255,0.08)', paddingTop: 18 }}>
      <a href="/" style={{
        fontSize: 12.5, color: 'rgba(255,255,255,0.55)',
        display: 'inline-flex', alignItems: 'center', gap: 6,
        textDecoration: 'none',
      }}>
        ← Back to home
      </a>
    </div>
  </div>
);

// ─── Summary / Done screen ──────────────────────────────────────
const Summary = ({ answers, palette, onRestart }) => {
  const rec = recommendPlan(answers) || PLAN_TABLE.small_shop_basic;
  const seePlansUrl = `/pricing?plan=${encodeURIComponent(rec.slug)}`;

  const summary = [
    { kicker: 'Starting point',  value: READABLE.start[answers.start] || '—' },
    { kicker: 'Operation',       value: READABLE.op[answers.op] || '—' },
    { kicker: answers.op === 'mobile' ? 'Crew' : 'Shop size', value: READABLE.size[answers.size] || '—' },
    { kicker: 'Weekly volume',   value: `~${answers.volume}${answers.volume >= 200 ? '+' : ''} cars / week` },
    { kicker: 'Primary goal',    value: READABLE.goal[answers.goal] || '—' },
    { kicker: 'Payments',        value: READABLE.square[answers.square] || '—' },
  ];

  return (
    <div>
      <div className="caption" style={{ marginBottom: 14 }}>All set</div>
      <h1 style={{
        margin: 0, fontSize: 38, lineHeight: 1.1, letterSpacing: '-0.025em', fontWeight: 600, textWrap: 'pretty',
      }}>
        Here's the plan we'd start you on.
      </h1>
      <p style={{ margin: '12px 0 28px', fontSize: 15.5, lineHeight: 1.5, color: 'rgba(11,18,32,0.6)', maxWidth: 560 }}>
        You can change plans, add features, or stack on add-ons any time from your subscription tab.
      </p>

      {/* Recommended plan card */}
      <div style={{
        background: '#0b1220', color: '#fff', borderRadius: 16, padding: '22px 24px',
        marginBottom: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24,
      }}>
        <div>
          <div className="caption" style={{ color: 'rgba(255,255,255,0.5)' }}>Recommended plan</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 8 }}>
            <div style={{ fontSize: 30, fontWeight: 600, letterSpacing: '-0.02em' }}>{rec.name}</div>
            <div className="mono" style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>{rec.monthly_price}</div>
          </div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)', marginTop: 6, maxWidth: 380, lineHeight: 1.5 }}>
            {rec.blurb}
          </div>
        </div>
        <EcoConstellation size={64} color={palette.color} accent={palette.accent} />
      </div>

      {/* Answer summary */}
      <div style={{
        background: '#fff', border: '1px solid rgba(11,18,32,0.10)', borderRadius: 16, overflow: 'hidden',
        marginBottom: 28,
      }}>
        {summary.map((row, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
            padding: '14px 20px',
            borderTop: i === 0 ? 'none' : '1px solid rgba(11,18,32,0.06)',
          }}>
            <div className="caption" style={{ minWidth: 130 }}>{row.kicker}</div>
            <div style={{ flex: 1, fontSize: 14.5, color: '#0b1220' }}>{row.value}</div>
            <button onClick={onRestart} style={{
              all: 'unset', cursor: 'pointer', fontSize: 12, color: 'rgba(11,18,32,0.5)',
            }}>Edit</button>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <PrimaryButton onClick={() => { window.location.href = seePlansUrl; }}>See plans</PrimaryButton>
        <span className="mono" style={{ fontSize: 11.5, color: 'rgba(11,18,32,0.45)' }}>
          Open {rec.name} on the pricing page →
        </span>
      </div>
    </div>
  );
};

// ─── Main App ───────────────────────────────────────────────────
const App = () => {
  // Tweaks panel removed — palette is fixed in production.
  const tweaks = { accent: 'blue', density: 'comfortable', showLogoPanel: true };
  const palette = ACCENT_OPTIONS[tweaks.accent] || ACCENT_OPTIONS.blue;

  const [stepIdx, setStepIdx] = useState(0);
  const [answers, setAnswers] = useState({
    start: null, op: null, size: null, volume: 25,
    goal: null, square: null,
  });
  const [done, setDone] = useState(false);
  const [transitionKey, setTransitionKey] = useState(0);

  const steps = useMemo(() => buildFlow(answers), [answers.op]);

  const setAnswer = (key, val) => setAnswers(prev => ({ ...prev, [key]: val }));

  const currentStep = steps[stepIdx];
  const isValid = (() => {
    if (!currentStep) return true;
    const v = answers[currentStep.id === 'size' ? 'size' : currentStep.id];
    if (currentStep.id === 'volume') return answers.volume > 0;
    return v != null;
  })();

  const goNext = () => {
    if (!isValid) return;
    if (stepIdx === steps.length - 1) {
      setDone(true);
    } else {
      setStepIdx(stepIdx + 1);
      setTransitionKey(k => k + 1);
    }
  };
  const goBack = () => {
    if (done) {
      setDone(false);
      setTransitionKey(k => k + 1);
      return;
    }
    if (stepIdx > 0) {
      setStepIdx(stepIdx - 1);
      setTransitionKey(k => k + 1);
    }
  };

  const restart = () => {
    setDone(false);
    setStepIdx(0);
    setTransitionKey(k => k + 1);
  };

  // Auto-advance after a brief delay when a choice is made on simple radio steps.
  const autoAdvanceRef = useRef(null);
  const handleAnswer = (key, val, autoAdvance = true) => {
    setAnswer(key, val);
    if (autoAdvance) {
      if (autoAdvanceRef.current) clearTimeout(autoAdvanceRef.current);
      autoAdvanceRef.current = setTimeout(() => {
        setStepIdx(prev => {
          const flow = buildFlow({ ...answers, [key]: val });
          if (prev === flow.length - 1) { setDone(true); return prev; }
          setTransitionKey(k => k + 1);
          return prev + 1;
        });
      }, 380);
    }
  };
  useEffect(() => () => { if (autoAdvanceRef.current) clearTimeout(autoAdvanceRef.current); }, []);

  // Render current question
  let questionEl = null;
  if (!done && currentStep) {
    switch (currentStep.id) {
      case 'start':
        questionEl = <QStartingPoint value={answers.start} onChange={(v) => handleAnswer('start', v)} />;
        break;
      case 'op':
        questionEl = <QOperationType value={answers.op}
          onChange={(v) => { setAnswers(p => ({ ...p, op: v, size: null })); setTimeout(() => { setStepIdx(s => s + 1); setTransitionKey(k => k + 1); }, 380); }} />;
        break;
      case 'size':
        questionEl = answers.op === 'mobile'
          ? <QMobileSize value={answers.size} onChange={(v) => handleAnswer('size', v)} />
          : <QShopSize value={answers.size} onChange={(v) => handleAnswer('size', v)} />;
        break;
      case 'volume':
        questionEl = <QVolume value={answers.volume} onChange={(v) => setAnswer('volume', v)} />;
        break;
      case 'goal':
        questionEl = <QGoal value={answers.goal} onChange={(v) => handleAnswer('goal', v)} />;
        break;
      case 'square':
        questionEl = <QSquare value={answers.square} onChange={(v) => handleAnswer('square', v)} />;
        break;
    }
  }

  const progressPct = done ? 100 : Math.round(((stepIdx) / steps.length) * 100);

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--paper)' }}>
      {tweaks.showLogoPanel && (
        <BrandPanel activeIdx={done ? steps.length : stepIdx} steps={steps} palette={palette} />
      )}

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <div style={{
          padding: '24px 48px 0', display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between',
        }}>
          <div style={{ flex: 1, maxWidth: 560, height: 4, background: 'rgba(11,18,32,0.08)', borderRadius: 999, overflow: 'hidden' }}>
            <div style={{
              width: progressPct + '%', height: '100%',
              background: '#0b1220',
              transition: 'width .5s cubic-bezier(.2,.7,.2,1)',
            }} />
          </div>
          <div className="mono" style={{ fontSize: 11.5, color: 'rgba(11,18,32,0.55)', whiteSpace: 'nowrap' }}>
            {done ? `Complete · 6 of 6` : `Step ${stepIdx + 1} of ${steps.length}`}
          </div>
        </div>

        <div style={{
          flex: 1, padding: '48px 48px 32px',
          display: 'flex', justifyContent: 'center', alignItems: 'flex-start',
        }}>
          <div style={{ width: '100%', maxWidth: 640 }}>
            <div key={transitionKey} className="q-enter">
              {done ? (
                <Summary answers={answers} palette={palette} onRestart={restart} />
              ) : questionEl}
            </div>
          </div>
        </div>

        {!done && (
          <div style={{
            padding: '20px 48px 32px',
            borderTop: '1px solid rgba(11,18,32,0.06)',
            background: 'rgba(255,255,255,0.4)',
            backdropFilter: 'blur(10px)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              {stepIdx > 0 ? (
                <GhostButton onClick={goBack}>Back</GhostButton>
              ) : (
                <span className="mono" style={{ fontSize: 11.5, color: 'rgba(11,18,32,0.4)' }}>
                  Press <kbd style={{ padding: '2px 6px', background: '#fff', border: '1px solid rgba(11,18,32,0.15)', borderRadius: 4, fontFamily: "'Geist Mono',monospace", fontSize: 10.5 }}>Enter</kbd> to continue
                </span>
              )}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              {currentStep && currentStep.id === 'volume' && (
                <span className="mono" style={{ fontSize: 11.5, color: 'rgba(11,18,32,0.45)' }}>
                  Drag the slider or pick a preset
                </span>
              )}
              <PrimaryButton onClick={goNext} disabled={!isValid}>
                {stepIdx === steps.length - 1 ? 'Review setup' : 'Continue'}
              </PrimaryButton>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Keyboard: Enter advances
window.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') {
    const btn = document.querySelector('[data-cc-primary]');
    if (btn && !btn.disabled) btn.click();
  }
});

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