﻿
const { useState } = React;

const CONTACT_EMAIL = 'hello@developerark.com';


const getSteps = () => [S.step1, S.step2, S.step3, S.step4];

const OrderFormPage = ({ navigate }) => {
  const STEPS = getSteps();
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({
    package: '',
    projectName: '', projectUrl: '', projectType: '',
    stage: '', techStack: '', teamSize: '',
    hasCI: '', hasBackup: '', hasSecurity: '',
    contactEmail: '', notes: '',
  });
  const buildFitCheckEmailHref = () => {
    const pkg = (window.PACKAGES || []).find(p => p.id === form.package);
    const subject = `Launch Ark fit check request — ${form.projectName || 'Unnamed project'}`;
    const lines = [
      'Launch Ark fit check',
      '',
      `Package: ${pkg ? pkg.name : form.package || '(not selected)'}`,
      `Project name: ${form.projectName || '(not provided)'}`,
      `Project URL: ${form.projectUrl || '(not provided)'}`,
      `Project type: ${form.projectType || '(not provided)'}`,
      `Stage: ${form.stage || '(not provided)'}`,
      `Tech stack: ${form.techStack || '(not provided)'}`,
      `Team size: ${form.teamSize || '(not provided)'}`,
      `CI/CD: ${form.hasCI || '(not provided)'}`,
      `Backup plan: ${form.hasBackup || '(not provided)'}`,
      `Security baseline: ${form.hasSecurity || '(not provided)'}`,
      `Contact email: ${form.contactEmail || '(not provided)'}`,
      `Notes: ${form.notes || '(none)'}`,
      '',
      'Fit check only. No payment is requested here.',
      'Do not send secrets, API keys, credentials, or private repository access.',
      'Scope and price should be confirmed by email before any work starts.',
    ];
    return `mailto:${CONTACT_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(lines.join('\n'))}`;
  };
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const canNext = [
    () => form.package !== '',
    () => form.projectName && form.projectType && form.stage,
    () => form.contactEmail && form.contactEmail.includes('@'),
    () => true,
  ][step];


  return (
    <div>
      {/* Header */}
      <section style={{ background: T.surface, borderBottom: `1px solid ${T.border}` }}>
        <Sec tight>
          <SectionLabel>{S.order_label}</SectionLabel>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <h1 style={{ fontFamily: T.sans, fontSize: 36, fontWeight: 700, color: T.text, letterSpacing: '-0.028em', margin: '0 0 10px' }}>
                {S.order_h1}
              </h1>
              <p style={{ fontFamily: T.sans, fontSize: 14.5, color: T.muted, margin: 0 }}>
                {S.order_sub}
              </p>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flexShrink: 0 }}>
              <div style={{ background: T.accentSubtle, border: `1px solid ${T.accentDim}`, borderRadius: 6, padding: '10px 16px' }}>
                <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.accentDim, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>
                  {S.order_no_secrets_label}
                </div>
                <div style={{ fontFamily: T.sans, fontSize: 12.5, color: T.muted, maxWidth: 260 }}>
                  {S.order_no_secrets_body}
                </div>
              </div>
              <div style={{ background: T.warningSubtle, border: `1px solid ${T.warning}33`, borderRadius: 6, padding: '8px 14px', fontFamily: T.mono, fontSize: 10, color: T.warning, letterSpacing: '0.04em', maxWidth: 260 }}>
                FIT CHECK ONLY В· NO PAYMENT AT THIS STAGE В· EMAIL CONFIRMATION REQUIRED
              </div>
            </div>
          </div>
        </Sec>
      </section>

      <Sec>
        {/* Step indicator */}
        <div style={{ display: 'flex', gap: 0, marginBottom: 48, alignItems: 'center' }}>
          {STEPS.map((s, i) => (
            <React.Fragment key={i}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{
                  width: 26, height: 26, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: i < step ? T.green : i === step ? T.accent : T.surface,
                  border: `1px solid ${i < step ? T.green : i === step ? T.accent : T.border}`,
                  fontFamily: T.mono, fontSize: 11, fontWeight: 600,
                  color: i <= step ? 'oklch(8% 0.01 52)' : T.muted,
                }}>
                  {i < step ? 'вњ“' : i + 1}
                </div>
                <span style={{
                  fontFamily: T.sans, fontSize: 13, fontWeight: i === step ? 600 : 400,
                  color: i === step ? T.text : T.muted,
                }}>
                  {s}
                </span>
              </div>
              {i < STEPS.length - 1 && (
                <div style={{ flex: 1, height: 1, background: i < step ? T.green : T.border, margin: '0 12px' }} />
              )}
            </React.Fragment>
          ))}
        </div>

        {/* Step content */}
        <div style={{ maxWidth: 640 }}>
          {step === 0 && <Step0 form={form} set={set} navigate={navigate} />}
          {step === 1 && <Step1 form={form} set={set} />}
          {step === 2 && <Step2 form={form} set={set} />}
          {step === 3 && <Step3 form={form} set={set} />}
        </div>

        {/* Navigation */}
        <div style={{ display: 'flex', gap: 12, marginTop: 40, maxWidth: 640 }}>
          {step > 0 && (
            <Btn variant="secondary" onClick={() => setStep(s => s - 1)}>{S.back}</Btn>
          )}
          <div style={{ flex: 1 }} />
          {step < STEPS.length - 1 ? (
            <Btn disabled={!canNext()} onClick={() => setStep(s => s + 1)}>{S.continue}</Btn>
          ) : (
            <a
              href={buildFitCheckEmailHref()}
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                minHeight: 40,
                padding: '0 18px',
                borderRadius: 6,
                background: T.text,
                color: T.bg,
                textDecoration: 'none',
                fontFamily: T.mono,
                fontSize: 11.5,
                fontWeight: 700,
                letterSpacing: '0.05em',
              }}
            >
              {S.submit}
            </a>
          )}
        </div>
        {step === 3 && (
          <div style={{ marginTop: 12, padding: '12px 14px', borderRadius: 6, background: T.surface, border: `1px solid ${T.border}`, fontFamily: T.sans, fontSize: 13, color: T.muted, lineHeight: 1.65 }}>
            Fit check only. No payment is requested here. Use the email draft to contact {CONTACT_EMAIL}. Do not submit secrets, API keys, credentials, or private repository access.
          </div>
        )}
      </Sec>
    </div>
  );
};

const FormField = ({ label, hint, children, required }) => (
  <div style={{ marginBottom: 24 }}>
    <label style={{
      display: 'block', fontFamily: T.sans, fontSize: 13.5, fontWeight: 500,
      color: T.text, marginBottom: 6,
    }}>
      {label} {required && <span style={{ color: T.accentDim }}>*</span>}
    </label>
    {hint && <div style={{ fontFamily: T.sans, fontSize: 12, color: T.dim, marginBottom: 8 }}>{hint}</div>}
    {children}
  </div>
);

const Input = ({ value, onChange, placeholder, type = 'text' }) => (
  <input
    type={type} value={value} onChange={e => onChange(e.target.value)}
    placeholder={placeholder}
    style={{
      width: '100%', background: T.surface, border: `1px solid ${T.border}`,
      borderRadius: 6, padding: '9px 14px', color: T.text,
      fontFamily: T.sans, fontSize: 14, outline: 'none', boxSizing: 'border-box',
    }}
  />
);

const Select = ({ value, onChange, options, placeholder }) => (
  <select
    value={value} onChange={e => onChange(e.target.value)}
    style={{
      width: '100%', background: T.surface, border: `1px solid ${T.border}`,
      borderRadius: 6, padding: '9px 14px', color: value ? T.text : T.muted,
      fontFamily: T.sans, fontSize: 14, outline: 'none', appearance: 'none',
      backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 8L1 3h10z'/%3E%3C/svg%3E")`,
      backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center',
    }}
  >
    <option value="">{placeholder}</option>
    {options.map(o => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
  </select>
);

const RadioGroup = ({ value, onChange, options }) => (
  <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
    {options.map(o => (
      <button key={o.value} type="button" onClick={() => onChange(o.value)}
        style={{
          padding: '7px 16px', borderRadius: 6, cursor: 'pointer',
          fontFamily: T.sans, fontSize: 13.5, fontWeight: value === o.value ? 600 : 400,
          background: value === o.value ? T.accentSubtle : T.surface,
          border: `1px solid ${value === o.value ? T.accentDim : T.border}`,
          color: value === o.value ? T.accent : T.muted,
          transition: 'all 0.12s',
        }}>
        {o.label}
      </button>
    ))}
  </div>
);

const Step0 = ({ form, set, navigate }) => (
  <div>
    <h2 style={{ fontFamily: T.sans, fontSize: 22, fontWeight: 600, color: T.text, margin: '0 0 8px' }}>{S.order_choose_pkg}</h2>
    <p style={{ fontFamily: T.sans, fontSize: 14, color: T.muted, margin: '0 0 28px' }}>
      {S.order_not_sure} <button onClick={() => navigate('pricing')} style={{ background: 'none', border: 'none', color: T.accent, cursor: 'pointer', fontFamily: T.sans, fontSize: 14, padding: 0 }}>{S.order_compare}</button>
    </p>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {(window.PACKAGES || []).map(pkg => (
        <button key={pkg.id} type="button" onClick={() => set('package', pkg.id)} style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          background: form.package === pkg.id ? T.accentSubtle : T.surface,
          border: `1px solid ${form.package === pkg.id ? T.accentDim : T.border}`,
          borderRadius: 8, padding: '16px 20px', cursor: 'pointer', transition: 'all 0.12s',
          textAlign: 'left',
        }}>
          <div>
            <div style={{ fontFamily: T.sans, fontSize: 15, fontWeight: 600, color: form.package === pkg.id ? T.accent : T.text, marginBottom: 2 }}>
              {pkg.name}
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 13, color: T.muted }}>{pkg.tagline} {pkg.forWho}</div>
          </div>
          <div style={{ fontFamily: T.mono, fontSize: 16, color: form.package === pkg.id ? T.accent : T.muted, fontWeight: 600, flexShrink: 0, marginLeft: 16 }}>
            {pkg.price}
          </div>
        </button>
      ))}
    </div>
  </div>
);

const Step1 = ({ form, set }) => (
  <div>
    <h2 style={{ fontFamily: T.sans, fontSize: 22, fontWeight: 600, color: T.text, margin: '0 0 28px' }}>{S.order_project_title}</h2>
    <FormField label={S.f_project_name} required>
      <Input value={form.projectName} onChange={v => set('projectName', v)} placeholder={S.f_pkg_ph} />
    </FormField>
    <FormField label={S.f_project_url} hint={S.f_project_url_hint}>
      <Input value={form.projectUrl} onChange={v => set('projectUrl', v)} placeholder={S.f_url_ph} />
    </FormField>
    <FormField label={S.f_project_type} required>
      <Select value={form.projectType} onChange={v => set('projectType', v)} placeholder={S.f_select_type}
        options={[S.f_web_app, S.f_mobile, S.f_api, S.f_cli, S.f_data, S.f_internal, S.f_other]} />
    </FormField>
    <FormField label={S.f_stage} required>
      <RadioGroup value={form.stage} onChange={v => set('stage', v)} options={[
        { value: 'pre-launch', label: S.f_pre },
        { value: 'launched',   label: S.f_launched },
        { value: 'production', label: S.f_prod },
        { value: 'legacy',     label: S.f_legacy },
      ]} />
    </FormField>
    <FormField label={S.f_tech_stack} hint={S.f_tech_stack_hint}>
      <Input value={form.techStack} onChange={v => set('techStack', v)} placeholder="e.g. Node.js, PostgreSQL" />
    </FormField>
    <FormField label={S.f_team_size}>
      <RadioGroup value={form.teamSize} onChange={v => set('teamSize', v)} options={[
        { value: '1',   label: S.f_solo },
        { value: '2-5', label: '2вЂ“5' },
        { value: '6-15',label: '6вЂ“15' },
        { value: '16+', label: '16+' },
      ]} />
    </FormField>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
      <FormField label={S.f_ci}>
        <RadioGroup value={form.hasCI} onChange={v => set('hasCI', v)} options={[{ value: 'yes', label: S.f_yes }, { value: 'no', label: S.f_no }, { value: 'partial', label: S.f_partial }]} />
      </FormField>
      <FormField label={S.f_backup}>
        <RadioGroup value={form.hasBackup} onChange={v => set('hasBackup', v)} options={[{ value: 'yes', label: S.f_yes }, { value: 'no', label: S.f_no }, { value: 'partial', label: S.f_partial }]} />
      </FormField>
      <FormField label={S.f_security_q}>
        <RadioGroup value={form.hasSecurity} onChange={v => set('hasSecurity', v)} options={[{ value: 'yes', label: S.f_yes }, { value: 'no', label: S.f_no }, { value: 'partial', label: S.f_partial }]} />
      </FormField>
    </div>
  </div>
);

const Step2 = ({ form, set }) => (
  <div>
    <h2 style={{ fontFamily: T.sans, fontSize: 22, fontWeight: 600, color: T.text, margin: '0 0 8px' }}>{S.order_contact_title}</h2>
    <p style={{ fontFamily: T.sans, fontSize: 14, color: T.muted, margin: '0 0 28px', lineHeight: 1.65 }}>
      {S.order_contact_sub}
    </p>
    <FormField label={S.f_email} required>
      <Input type="email" value={form.contactEmail} onChange={v => set('contactEmail', v)} placeholder={S.f_email_ph} />
    </FormField>
    <FormField label={S.f_notes} hint={S.f_notes_hint}>
      <textarea value={form.notes} onChange={e => set('notes', e.target.value)}
        placeholder={S.f_notes_ph}
        rows={4}
        style={{
          width: '100%', background: T.surface, border: `1px solid ${T.border}`,
          borderRadius: 6, padding: '9px 14px', color: T.text,
          fontFamily: T.sans, fontSize: 14, outline: 'none', resize: 'vertical',
          lineHeight: 1.6, boxSizing: 'border-box',
        }}
      />
    </FormField>
  </div>
);

const Step3 = ({ form }) => {
  const pkg = (window.PACKAGES || []).find(p => p.id === form.package);
  const rows = [
    [S.review_package, pkg ? pkg.name : 'вЂ”'],
    [S.review_project, form.projectName || 'вЂ”'],
    [S.review_type,    form.projectType || 'вЂ”'],
    [S.review_stage,   form.stage || 'вЂ”'],
    [S.review_stack,   form.techStack || 'вЂ”'],
    [S.review_team,    form.teamSize || 'вЂ”'],
    [S.review_email,   form.contactEmail || 'вЂ”'],
  ];
  return (
    <div>
      <h2 style={{ fontFamily: T.sans, fontSize: 22, fontWeight: 600, color: T.text, margin: '0 0 8px' }}>{S.order_review_title}</h2>
      <p style={{ fontFamily: T.sans, fontSize: 14, color: T.muted, margin: '0 0 28px' }}>
        {S.order_review_sub}
      </p>
      <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8, overflow: 'hidden', marginBottom: 24 }}>
        {rows.map(([k, v], i) => (
          <div key={i} style={{
            display: 'flex', gap: 16, padding: '12px 20px',
            borderBottom: i < rows.length - 1 ? `1px solid ${T.border}` : 'none',
            background: i % 2 === 0 ? 'transparent' : T.surfaceRaised,
          }}>
            <span style={{ fontFamily: T.mono, fontSize: 11.5, color: T.muted, minWidth: 120, letterSpacing: '0.02em' }}>{k}</span>
            <span style={{ fontFamily: T.sans, fontSize: 13.5, color: T.text }}>{v}</span>
          </div>
        ))}
      </div>
      <div style={{
        background: T.accentSubtle, border: `1px solid ${T.accentDim}`,
        borderRadius: 6, padding: '14px 18px',
        fontFamily: T.sans, fontSize: 13, color: T.muted, lineHeight: 1.65,
      }}>
        {S.order_confirm_no_secrets} <strong style={{ color: T.accent }}>{S.order_confirm_keys}</strong>.
      </div>
    </div>
  );
};

window.OrderFormPage = OrderFormPage;



