/* =====================================================================
   Mereka v2 - Flow stubs added per Design Review (Section 8 UX Flows)
   Registration (3-step, phone + BM), Enrollment confirmation,
   Certificate, Empty states, Marketplace launch/waitlist state.
   All brand-token compliant (teal primary, off-black text, Poppins headings).
   ===================================================================== */

/* ---------- shared bits ---------- */
function FlowStepper({ steps, current }) {
  return (
    <div className="flex items-center gap-2 mb-8">
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          <div className="flex items-center gap-2">
            <span className={`w-7 h-7 rounded-full flex items-center justify-center text-[13px] font-bold ${i <= current ? 'bg-primary text-ink' : 'bg-neutral-200 text-neutral-500'}`}>
              {i < current ? <Icon name="check" size={14} /> : i + 1}
            </span>
            <span className={`text-[13px] font-semibold ${i === current ? 'text-ink' : 'text-neutral-400'} hidden sm:inline`} style={{ fontFamily: _pp }}>{s}</span>
          </div>
          {i < steps.length - 1 && <span className="flex-1 h-px bg-neutral-200 min-w-[16px]" />}
        </React.Fragment>
      ))}
    </div>
  );
}

function FlowEmptyState({ icon = "compass", title, body, cta, to, onAction }) {
  return (
    <div className="text-center py-16 px-6 rounded-2xl border border-dashed border-neutral-300 bg-surface">
      <div className="w-16 h-16 rounded-2xl bg-primary-light text-primary-700 mx-auto flex items-center justify-center mb-4">
        <Icon name={icon} size={28} />
      </div>
      <h3 className="text-xl font-bold text-ink" style={{ fontFamily: _pp }}>{title}</h3>
      <p className="mt-2 text-[15px] text-neutral-600 max-w-md mx-auto leading-relaxed">{body}</p>
      {cta && (to
        ? <Link to={to} className="inline-flex mt-6"><Button variant="primary">{cta}</Button></Link>
        : <button onClick={onAction} className="mt-6"><Button variant="primary">{cta}</Button></button>)}
    </div>
  );
}

/* ---------- 1. Registration (max 3 steps, phone option + BM) ---------- */
function RegisterFlowPage() {
  const steps = ['Account', 'Interests', 'Confirm'];
  const [step, setStep] = React.useState(0);
  const [method, setMethod] = React.useState('phone');
  const [done, setDone] = React.useState(false);
  const interests = ['AI & Data', 'Design', 'Marketing', 'Business', 'Web Dev', 'Sustainability', 'Wellbeing', 'Finance'];
  const [picked, setPicked] = React.useState([]);
  const toggle = t => setPicked(p => p.includes(t) ? p.filter(x => x !== t) : [...p, t]);

  if (done) {
    return (
      <PublicShell route="/app/register">
        <div className="max-w-lg mx-auto px-5 py-16 text-center">
          <div className="w-20 h-20 rounded-2xl bg-primary text-ink mx-auto flex items-center justify-center mb-6"><Icon name="check" size={40} /></div>
          <h1 className="text-3xl font-bold text-ink" style={{ fontFamily: _pp }}>You're all set!</h1>
          <p className="mt-3 text-neutral-600">Your Mereka account is ready. Jump into your dashboard to resume learning, browse programs, or find work.</p>
          <Link to="/app/dashboard/overview" className="inline-flex mt-7"><Button variant="primary" size="lg">Go to my dashboard</Button></Link>
        </div>
      </PublicShell>
    );
  }

  return (
    <PublicShell route="/app/register">
      <div className="max-w-lg mx-auto px-5 py-10">
        <div className="flex items-center justify-between mb-6">
          <div style={{ height: 30 }}><MerekaLogo /></div>
          <LangToggle />
        </div>
        <FlowStepper steps={steps} current={step} />

        {step === 0 && (
          <Card className="p-6">
            <h1 className="text-2xl font-bold text-ink mb-1" style={{ fontFamily: _pp }}>Create your account</h1>
            <p className="text-[14px] text-neutral-500 mb-5">Sign up in under a minute. No email? Use your phone number.</p>
            <div className="flex gap-2 mb-4">
              {[['phone', 'Phone number'], ['email', 'Email']].map(([k, l]) => (
                <button key={k} onClick={() => setMethod(k)} className={`flex-1 h-11 rounded-full text-sm font-semibold border transition-colors ${method === k ? 'border-primary bg-primary-light text-primary-700' : 'border-neutral-200 text-neutral-600'}`}>{l}</button>
              ))}
            </div>
            <label className="block text-[13px] font-semibold text-neutral-700 mb-1.5">{method === 'phone' ? 'Phone number' : 'Email address'}</label>
            {method === 'phone' ? (
              <div className="flex gap-2">
                <span className="h-12 px-3 inline-flex items-center rounded-xl border border-neutral-300 bg-surface text-sm font-medium text-neutral-700">🇲🇾 +60</span>
                <input inputMode="numeric" placeholder="12 345 6789" className="flex-1 h-12 px-4 rounded-xl border border-neutral-300 focus:border-primary focus:outline-none" />
              </div>
            ) : (
              <input type="email" placeholder="you@example.com" className="w-full h-12 px-4 rounded-xl border border-neutral-300 focus:border-primary focus:outline-none" />
            )}
            <p className="mt-2 text-[12px] text-neutral-400">We'll send a one-time code to verify. Standard rates may apply.</p>
            <button onClick={() => setStep(1)} className="mt-5 w-full"><Button variant="primary" size="lg" className="w-full">Continue</Button></button>
            <p className="mt-4 text-center text-[13px] text-neutral-500">Already have an account? <Link to="/app/login" className="text-primary-700 font-semibold">Log in</Link></p>
          </Card>
        )}

        {step === 1 && (
          <Card className="p-6">
            <h1 className="text-2xl font-bold text-ink mb-1" style={{ fontFamily: _pp }}>What do you want to learn?</h1>
            <p className="text-[14px] text-neutral-500 mb-5">Pick a few and we'll tailor your programs and gigs.</p>
            <div className="flex flex-wrap gap-2">
              {interests.map(t => (
                <button key={t} onClick={() => toggle(t)} className={`px-4 h-11 rounded-full text-sm font-semibold border transition-colors ${picked.includes(t) ? 'border-primary bg-primary-light text-primary-700' : 'border-neutral-200 text-neutral-600 hover:border-neutral-300'}`}>{t}</button>
              ))}
            </div>
            <div className="flex gap-2 mt-7">
              <button onClick={() => setStep(0)}><Button variant="secondary" size="lg">Back</Button></button>
              <button onClick={() => setStep(2)} className="flex-1"><Button variant="primary" size="lg" className="w-full">Continue</Button></button>
            </div>
          </Card>
        )}

        {step === 2 && (
          <Card className="p-6">
            <h1 className="text-2xl font-bold text-ink mb-1" style={{ fontFamily: _pp }}>Almost there</h1>
            <p className="text-[14px] text-neutral-500 mb-5">Confirm and we'll set up your dashboard.</p>
            <div className="rounded-xl bg-surface p-4 text-sm text-neutral-700 space-y-2">
              <div className="flex justify-between"><span className="text-neutral-500">Sign-up method</span><span className="font-semibold">{method === 'phone' ? 'Phone (+60)' : 'Email'}</span></div>
              <div className="flex justify-between"><span className="text-neutral-500">Interests</span><span className="font-semibold">{picked.length ? picked.length + ' selected' : 'Skip for now'}</span></div>
              <div className="flex justify-between"><span className="text-neutral-500">Language</span><span className="font-semibold">EN / BM</span></div>
            </div>
            <label className="flex items-start gap-2 mt-4 text-[13px] text-neutral-600">
              <input type="checkbox" defaultChecked className="mt-0.5 accent-[#1FA3A6]" />
              <span>I agree to Mereka's Terms of Use and Privacy Policy.</span>
            </label>
            <div className="flex gap-2 mt-6">
              <button onClick={() => setStep(1)}><Button variant="secondary" size="lg">Back</Button></button>
              <button onClick={() => setDone(true)} className="flex-1"><Button variant="primary" size="lg" className="w-full">Create account</Button></button>
            </div>
          </Card>
        )}
      </div>
    </PublicShell>
  );
}

/* ---------- 2. Enrollment confirmation ---------- */
function EnrollConfirmPage({ slug }) {
  const name = (slug || 'ai-fundamentals').replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
  const [enrolled, setEnrolled] = React.useState(false);
  return (
    <PublicShell route={'/app/enroll/' + slug}>
      <div className="max-w-xl mx-auto px-5 py-12">
        {!enrolled ? (
          <Card className="p-7">
            <PillarTag name={name} className="mb-3" />
            <h1 className="text-2xl font-bold text-ink" style={{ fontFamily: _pp }}>{name}</h1>
            <p className="mt-2 text-[15px] text-neutral-600">Confirm your enrollment. You'll get access to all modules, office hours, and a certificate on completion.</p>
            <div className="rounded-xl bg-surface p-4 mt-5 space-y-2 text-sm">
              <div className="flex justify-between"><span className="text-neutral-500">Format</span><span className="font-semibold text-ink">Self-paced + live office hours</span></div>
              <div className="flex justify-between"><span className="text-neutral-500">Duration</span><span className="font-semibold text-ink">2 weeks</span></div>
              <div className="flex justify-between"><span className="text-neutral-500">Certificate</span><span className="font-semibold text-ink">Yes, on completion</span></div>
              <div className="flex justify-between"><span className="text-neutral-500">Price</span><span className="font-semibold text-primary-700">FREE (sponsored)</span></div>
            </div>
            <button onClick={() => setEnrolled(true)} className="mt-6 w-full"><Button variant="primary" size="lg" className="w-full">Join this programme</Button></button>
            <p className="mt-3 text-center text-[12px] text-neutral-400">"Join" adds this to your dashboard. No payment required.</p>
          </Card>
        ) : (
          <div className="text-center">
            <div className="w-20 h-20 rounded-2xl bg-primary text-ink mx-auto flex items-center justify-center mb-6"><Icon name="check" size={40} /></div>
            <h1 className="text-3xl font-bold text-ink" style={{ fontFamily: _pp }}>You're enrolled!</h1>
            <p className="mt-3 text-neutral-600 max-w-md mx-auto">{name} is now in your dashboard. Start module 1 whenever you're ready. Your certificate unlocks when you finish.</p>
            <div className="flex gap-2 justify-center mt-7 flex-wrap">
              <Link to="/app/dashboard/programmes"><Button variant="primary" size="lg">Start learning</Button></Link>
              <Link to="/app/dashboard/overview"><Button variant="secondary" size="lg">Go to dashboard</Button></Link>
            </div>
          </div>
        )}
      </div>
    </PublicShell>
  );
}

/* ---------- 3. Certificate / achievement ---------- */
function CertificatePage({ id }) {
  const program = (id || 'ai-fundamentals').replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
  return (
    <PublicShell route={'/app/certificate/' + id}>
      <div className="max-w-3xl mx-auto px-5 py-12">
        <div className="rounded-2xl border-2 border-primary p-8 lg:p-12 bg-white relative overflow-hidden">
          <div className="absolute -top-16 -right-16 w-56 h-56 rounded-full bg-primary-xlight" />
          <div className="relative">
            <div className="flex items-center justify-between mb-8">
              <div style={{ height: 34 }}><MerekaLogo /></div>
              <PillarTag name={program} />
            </div>
            <p className="text-[13px] font-bold uppercase tracking-[0.18em] text-primary-700" style={{ fontFamily: _pp }}>Certificate of Completion</p>
            <p className="mt-6 text-[15px] text-neutral-500">This certifies that</p>
            <h1 className="mt-1 text-4xl font-bold text-ink" style={{ fontFamily: _pp }}>Faiz Fadhillah</h1>
            <p className="mt-4 text-[15px] text-neutral-500">has successfully completed</p>
            <h2 className="mt-1 text-2xl font-bold text-ink" style={{ fontFamily: _pp }}>{program}</h2>
            <div className="flex flex-wrap gap-8 mt-8 pt-6 border-t border-neutral-200 text-sm">
              <div><p className="text-neutral-400 text-[12px] uppercase tracking-wide">Issued</p><p className="font-semibold text-ink">28 July 2026</p></div>
              <div><p className="text-neutral-400 text-[12px] uppercase tracking-wide">Credential ID</p><p className="font-semibold text-ink num-tabular">MRK-{(id || 'AIF').slice(0, 3).toUpperCase()}-2026-0417</p></div>
              <div><p className="text-neutral-400 text-[12px] uppercase tracking-wide">Verify at</p><p className="font-semibold text-primary-700">mereka.io/verify</p></div>
            </div>
          </div>
        </div>
        <div className="flex gap-2 justify-center mt-6 flex-wrap">
          <Button variant="primary" leftIcon="download">Download PDF</Button>
          <Button variant="secondary" leftIcon="external">Share to LinkedIn</Button>
        </div>
      </div>
    </PublicShell>
  );
}

/* ---------- 4. New-user empty dashboard ---------- */
function NewUserStartPage() {
  return (
    <UserShell route="/app/dashboard/start" title="Welcome to Mereka">
      <div className="max-w-3xl">
        <FlowEmptyState
          icon="spark"
          title="Let's get you started"
          body="You haven't enrolled in anything yet. Browse programmes to build in-demand skills, or explore gigs to start earning."
          cta="Browse programmes" to="/web/programs" />
        <div className="grid sm:grid-cols-3 gap-4 mt-6">
          {[['book', 'Explore courses', '/web/courses'], ['briefcase', 'Find work', '/web/jobs'], ['user', 'Complete your profile', '/app/dashboard/settings']].map(([ic, t, to]) => (
            <Link key={t} to={to} className="p-5 rounded-2xl border border-neutral-200 hover:border-primary hover:shadow-md transition-all">
              <div className="w-10 h-10 rounded-xl bg-primary-light text-primary-700 flex items-center justify-center mb-3"><Icon name={ic} size={20} /></div>
              <p className="font-bold text-ink" style={{ fontFamily: _pp }}>{t}</p>
            </Link>
          ))}
        </div>
      </div>
    </UserShell>
  );
}

/* ---------- 5. Talent marketplace launch / waitlist ---------- */
function TalentWaitlistPage() {
  const [joined, setJoined] = React.useState(false);
  return (
    <PublicShell route="/web/talent">
      <div className="max-w-2xl mx-auto px-5 py-16 text-center">
        <span className="inline-flex items-center gap-1.5 px-3 h-7 rounded-full bg-primary-light text-primary-700 text-[12px] font-bold uppercase tracking-wide mb-5">Coming soon</span>
        <h1 className="text-4xl font-bold text-ink" style={{ fontFamily: _pp }}>The Mereka Talent Marketplace</h1>
        <p className="mt-4 text-lg text-neutral-600">Hire vetted Malaysian talent for projects and gigs, or list your own services. We're onboarding our first cohort of experts now.</p>
        {!joined ? (
          <div className="mt-8 flex gap-2 max-w-md mx-auto">
            <input placeholder="Your email or phone" className="flex-1 h-12 px-4 rounded-full border border-neutral-300 focus:border-primary focus:outline-none" />
            <button onClick={() => setJoined(true)}><Button variant="primary" size="lg">Join waitlist</Button></button>
          </div>
        ) : (
          <div className="mt-8 inline-flex items-center gap-2 px-5 h-12 rounded-full bg-primary-light text-primary-700 font-semibold"><Icon name="check" size={18} /> You're on the list. We'll be in touch.</div>
        )}
        <p className="mt-6 text-[13px] text-neutral-400">Already an expert with Mereka? <Link to="/app/onboarding/expert/welcome" className="text-primary-700 font-semibold">Set up your profile</Link></p>
      </div>
    </PublicShell>
  );
}

Object.assign(window, {
  FlowStepper, FlowEmptyState,
  RegisterFlowPage, EnrollConfirmPage, CertificatePage, NewUserStartPage, TalentWaitlistPage,
});
