// Commission flow — stepped, calm, and now real.
//
// Collects room, mood, size, budget, notes, and an artist pick. The final
// step writes to Supabase via the commissions-create Edge Function. If the
// user isn't signed in, the parent routes them through AuthScreen first and
// this screen auto-submits once they return.
//
// Three small SVG animations live at the bottom of the file:
//   • BrushStroke — a calligraphic flourish drawing itself (step hero).
//   • InkBloom    — concentric ripples while the request is in flight.
//   • EightReveal — the 888 mark easing in on success.

function CommissionScreen({ onBack, user, onNeedSignIn }) {
  const [step, setStep] = React.useState(0);
  const [room, setRoom] = React.useState(null);
  const [roomNote, setRoomNote] = React.useState('');
  const [mood, setMood] = React.useState('Morning light');
  const [size, setSize] = React.useState('Medium');
  const [budget, setBudget] = React.useState(1200);
  // Every commission is painted by 888 Studio — no artist picker.
  const artistSlug = 'studio-888';

  // idle → auth_pending → submitting → success | error
  const [phase, setPhase] = React.useState('idle');
  const [commission, setCommission] = React.useState(null);
  const [error, setError] = React.useState(null);

  const steps = ['Room', 'Feeling', 'Size', 'Review'];
  const hasBackend = !!window.api?.hasBackend;

  const submit = React.useCallback(async () => {
    setPhase('submitting');
    setError(null);
    try {
      if (!hasBackend) {
        // Demo mode: no backend wired up. Fake a short_id so the flow feels
        // complete for designers clicking around.
        await new Promise((r) => setTimeout(r, 1400));
        setCommission({ short_id: `C${Math.floor(1000 + Math.random() * 9000)}`, status: 'submitted' });
        setPhase('success');
        return;
      }
      const c = await window.api.createCommission({
        room,
        mood: `${mood}${roomNote ? ` — ${roomNote}` : ''}`,
        size,
        budget,
        notes: roomNote,
        artistSlug,
      });
      setCommission(c);
      setPhase('success');
    } catch (err) {
      setError(err.message || 'Something went wrong. Try again?');
      setPhase('error');
    }
  }, [hasBackend, room, mood, roomNote, size, budget, artistSlug]);

  const onPlaceCommission = () => {
    if (hasBackend && !user) {
      setPhase('auth_pending');
      onNeedSignIn?.();
      return;
    }
    submit();
  };

  // If we were waiting on sign-in and the user is now signed in, continue.
  React.useEffect(() => {
    if (phase === 'auth_pending' && user) submit();
  }, [user, phase, submit]);

  const disableSubmit = phase === 'submitting' || phase === 'success';

  if (phase === 'success' && commission) {
    return <CommissionSuccess commission={commission} onBack={onBack}/>;
  }

  return (
    <>
      <style>{commissionAnimationsCss}</style>
      <AppHeader title="Commission" onBack={step === 0 ? onBack : () => setStep(step - 1)}/>

      {/* Step indicator */}
      <div style={{ padding: '14px 20px 8px', display: 'flex', gap: 6 }}>
        {steps.map((s, i) => (
          <div key={s} style={{
            flex: 1, height: 3, borderRadius: 2,
            background: i <= step ? 'var(--ink-500)' : 'var(--line)',
            transition: 'background 320ms var(--ease-out)',
          }}/>
        ))}
      </div>
      <div style={{ padding: '6px 20px 10px', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-faint)', letterSpacing: '0.1em' }}>
        STEP {step + 1} OF {steps.length} · {steps[step].toUpperCase()}
      </div>

      <div style={{ padding: '18px 20px 140px' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
          <BrushStroke width={140}/>
        </div>

        {step === 0 && <StepRoom room={room} setRoom={setRoom} note={roomNote} setNote={setRoomNote}/>}
        {step === 1 && <StepFeeling mood={mood} setMood={setMood}/>}
        {step === 2 && <StepSize size={size} setSize={setSize} budget={budget} setBudget={setBudget}/>}
        {step === 3 && <StepReview room={room} mood={mood} size={size} budget={budget} note={roomNote}/>}

        {phase === 'error' && error && (
          <div style={{
            marginTop: 20, padding: '12px 16px', borderRadius: 'var(--r-sm)',
            background: 'rgba(215, 89, 52, 0.08)', color: 'var(--accent)',
            fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.5,
          }}>{error}</div>
        )}
      </div>

      {/* Sticky footer — either Continue, a submit button, or the in-flight state */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, padding: '14px 20px calc(22px + env(safe-area-inset-bottom))',
        background: 'rgba(251,247,236,0.92)', backdropFilter: 'blur(12px)',
        borderTop: '1px solid var(--line)',
      }}>
        {phase === 'submitting' || phase === 'auth_pending' ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '4px 0' }}>
            <InkBloom size={44}/>
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, color: 'var(--fg)' }}>
                {phase === 'auth_pending' ? 'Waiting for sign-in…' : 'Sending to the studio…'}
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>
                This takes a beat. Breathe.
              </div>
            </div>
          </div>
        ) : step < steps.length - 1 ? (
          <Button variant="primary" full iconRight="arrowRight" onClick={() => setStep(step + 1)}>
            Continue
          </Button>
        ) : (
          <Button variant="accent" full disabled={disableSubmit} onClick={onPlaceCommission}>
            {phase === 'error' ? 'Try again' : 'Place commission'}
          </Button>
        )}
      </div>
    </>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// Steps

function StepRoom({ room, setRoom, note, setNote }) {
  const rooms = ['Bedroom', 'Living room', 'Entryway', 'Reading nook', 'Office', 'Kitchen'];
  return (
    <>
      <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 400, lineHeight: 1.2, color: 'var(--fg)' }}>
        Tell us about the room.
      </h2>
      <p style={{ margin: '10px 0 18px', fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 15, color: 'var(--fg-muted)', lineHeight: 1.5 }}>
        Where will it live? We paint for the space, not just the wall.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
        {rooms.map((r) => {
          const active = room === r;
          return (
            <button key={r} onClick={() => setRoom(r)} style={{
              padding: '18px 14px', borderRadius: 'var(--r-md)',
              border: `1px solid ${active ? 'var(--ink-500)' : 'var(--line)'}`,
              background: active ? 'var(--ink-500)' : 'var(--bg-elevated)',
              color: active ? 'var(--fg-on-ink)' : 'var(--fg)', textAlign: 'left',
              fontFamily: 'var(--font-display)', fontSize: 15, cursor: 'pointer',
              transition: 'all 160ms var(--ease-out)',
            }}>{r}</button>
          );
        })}
      </div>
      <div style={{ marginTop: 8 }}>
        <Eyebrow style={{ marginBottom: 8 }}>Anything else?</Eyebrow>
        <textarea
          value={note}
          onChange={(e) => setNote(e.target.value)}
          placeholder="A reading nook with soft afternoon light. Warm woods, linen chair. Looking for something that feels like a slow morning."
          style={{
            width: '100%', boxSizing: 'border-box', padding: '14px 16px',
            background: 'var(--bg-sunken)', border: '1px solid var(--line)',
            borderRadius: 'var(--r-sm)', fontFamily: 'var(--font-display)', fontSize: 15,
            color: 'var(--fg)', minHeight: 90, resize: 'vertical', outline: 'none', lineHeight: 1.5,
          }}
        />
      </div>
    </>
  );
}

function StepFeeling({ mood, setMood }) {
  const moods = ['Morning light', 'Quiet storm', 'Warm evening', 'Deep forest', 'Open sea', 'First snow'];
  return (
    <>
      <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 400, lineHeight: 1.2, color: 'var(--fg)' }}>
        What should it feel like?
      </h2>
      <p style={{ margin: '10px 0 20px', fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 15, color: 'var(--fg-muted)' }}>
        Pick a weather. A memory. A mood.
      </p>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {moods.map((m) => <Chip key={m} active={mood === m} onClick={() => setMood(m)}>{m}</Chip>)}
      </div>
    </>
  );
}

function StepSize({ size, setSize, budget, setBudget }) {
  const sizes = [
    { label: 'Small', dim: '12 × 16 in' },
    { label: 'Medium', dim: '24 × 36 in' },
    { label: 'Large', dim: '36 × 48 in' },
  ];
  return (
    <>
      <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 400, lineHeight: 1.2, color: 'var(--fg)' }}>
        How big? How much?
      </h2>
      <div style={{ margin: '24px 0 8px' }}><Eyebrow>Size</Eyebrow></div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
        {sizes.map((s) => {
          const active = size === s.label;
          return (
            <button key={s.label} onClick={() => setSize(s.label)} style={{
              padding: '16px 10px', borderRadius: 'var(--r-md)',
              border: `1px solid ${active ? 'var(--ink-500)' : 'var(--line)'}`,
              background: active ? 'var(--ink-500)' : 'var(--bg-elevated)',
              color: active ? 'var(--fg-on-ink)' : 'var(--fg)', cursor: 'pointer',
              transition: 'all 160ms var(--ease-out)',
            }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 16 }}>{s.label}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, opacity: 0.7, marginTop: 4 }}>{s.dim}</div>
            </button>
          );
        })}
      </div>
      <div style={{ margin: '24px 0 8px' }}><Eyebrow>Budget</Eyebrow></div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 40, fontWeight: 500, color: 'var(--fg)' }}>
        ${budget.toLocaleString()}
      </div>
      <input
        type="range" min="400" max="5000" step="100"
        value={budget} onChange={(e) => setBudget(+e.target.value)}
        style={{ width: '100%', accentColor: 'var(--ink-500)' }}
      />
      <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-faint)', marginTop: 4 }}>
        <span>$400</span><span>$5,000</span>
      </div>
    </>
  );
}

function StepReview({ room, mood, size, budget, note }) {
  const sizeMap = { Small: '12 × 16 in', Medium: '24 × 36 in', Large: '36 × 48 in' };
  const rows = [
    { label: 'Room',    value: room || '—' },
    { label: 'Feeling', value: mood },
    { label: 'Size',    value: `${size} · ${sizeMap[size] || ''}` },
    { label: 'Budget',  value: `$${budget.toLocaleString()}` },
  ];
  if (note && note.trim()) rows.push({ label: 'Notes', value: note.trim() });

  return (
    <>
      <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 400, lineHeight: 1.2, color: 'var(--fg)' }}>
        Ready to begin.
      </h2>
      <p style={{ margin: '10px 0 22px', fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 15, color: 'var(--fg-muted)' }}>
        Painted in-house at 888 Studio. Every piece signed and tucked with a handwritten note.
      </p>

      {/* Studio card */}
      <div style={{
        display: 'flex', gap: 14, padding: 16, borderRadius: 'var(--r-md)',
        background: 'var(--surface-ink)', color: 'var(--fg-on-ink)', alignItems: 'center', marginBottom: 18,
      }}>
        <Disk size={56}>888</Disk>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 10, letterSpacing: '0.18em', color: 'var(--fg-on-ink-muted)' }}>
            YOUR STUDIO
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, color: 'var(--fg-on-ink)', marginTop: 2 }}>
            888 Studio
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-on-ink-muted)' }}>
            — Brooklyn, eight days to first sketch
          </div>
        </div>
      </div>

      {/* Summary */}
      <div style={{ borderTop: '1px solid var(--line)' }}>
        {rows.map((r) => (
          <div key={r.label} style={{
            display: 'flex', gap: 16, padding: '14px 2px', borderBottom: '1px solid var(--line)',
            alignItems: 'baseline',
          }}>
            <div style={{
              width: 90, flexShrink: 0,
              fontFamily: 'var(--font-body)', fontSize: 10, letterSpacing: '0.18em',
              textTransform: 'uppercase', color: 'var(--fg-muted)',
            }}>{r.label}</div>
            <div style={{
              flex: 1, fontFamily: 'var(--font-display)', fontSize: 15,
              color: 'var(--fg)', lineHeight: 1.45,
            }}>{r.value}</div>
          </div>
        ))}
      </div>
    </>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// Success

function CommissionSuccess({ commission, onBack }) {
  return (
    <>
      <style>{commissionAnimationsCss}</style>
      <AppHeader title=""/>
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        textAlign: 'center', padding: '40px 28px 140px',
      }}>
        <EightReveal size={140}/>

        <div style={{ marginTop: 28, fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '0.18em', color: 'var(--fg-muted)' }}>
          COMMISSION №{commission.short_id}
        </div>
        <h1 style={{
          margin: '10px 0 10px', fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 400,
          lineHeight: 1.12, letterSpacing: '-0.01em', color: 'var(--fg)',
        }}>
          It's in. <em style={{ fontWeight: 400 }}>Eight days to first sketch.</em>
        </h1>
        <p style={{
          margin: '6px 0 0', maxWidth: 340,
          fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 15,
          color: 'var(--fg-muted)', lineHeight: 1.55,
        }}>
          The artist will reach out within a day or two with a first note and a few questions.
          We'll keep you posted in Studio.
        </p>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, width: '100%', maxWidth: 320, marginTop: 32 }}>
          <Button variant="primary" full onClick={onBack}>Back to browse</Button>
        </div>
      </div>
    </>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// Animations

// A single calligraphy arc drawing itself, looping. Deliberately slow so it
// reads as a breath rather than a progress bar.
function BrushStroke({ width = 140, color = 'var(--ink-500)' }) {
  return (
    <svg width={width} height={width * 0.36} viewBox="0 0 200 72" aria-hidden="true">
      <path
        d="M 12 54 Q 52 6, 100 36 T 188 28"
        fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round"
        style={{
          strokeDasharray: 260,
          strokeDashoffset: 260,
          animation: 'c888-draw 3.2s cubic-bezier(0.65,0,0.35,1) infinite',
        }}
      />
      <circle cx="188" cy="28" r="3" fill={color} style={{
        opacity: 0,
        animation: 'c888-dot 3.2s cubic-bezier(0.65,0,0.35,1) infinite',
      }}/>
    </svg>
  );
}

// Two soft ink ripples spreading outward from a dark center. Loading indicator
// with the emotional weight of a sumi-e drop hitting paper.
function InkBloom({ size = 60, color = 'var(--ink-500)' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 60 60" aria-hidden="true">
      <circle cx="30" cy="30" r="6" fill={color} fillOpacity="0.25" style={{
        animation: 'c888-bloom 1.6s ease-out 0s infinite',
      }}/>
      <circle cx="30" cy="30" r="6" fill={color} fillOpacity="0.25" style={{
        animation: 'c888-bloom 1.6s ease-out 0.55s infinite',
      }}/>
      <circle cx="30" cy="30" r="5" fill={color}/>
    </svg>
  );
}

// The 888 mark arriving on success: ink disk fades in, cream disk blooms,
// "888" fades in last. Plays once.
function EightReveal({ size = 140 }) {
  const gid = React.useId ? React.useId() : `er-${Math.random().toString(36).slice(2, 8)}`;
  return (
    <svg width={size} height={size} viewBox="0 0 140 140" aria-hidden="true">
      <defs>
        <radialGradient id={`ink-${gid}`} cx="0.38" cy="0.32" r="0.82">
          <stop offset="0%" stopColor="#3a3a38"/>
          <stop offset="55%" stopColor="#121210"/>
          <stop offset="100%" stopColor="#000"/>
        </radialGradient>
        <radialGradient id={`cream-${gid}`} cx="0.42" cy="0.36" r="0.75">
          <stop offset="0%" stopColor="#fcf5e3"/>
          <stop offset="70%" stopColor="#f1e7cc"/>
          <stop offset="100%" stopColor="#d9caa4"/>
        </radialGradient>
      </defs>
      <g style={{ transformOrigin: '70px 70px', animation: 'c888-breathe 4s ease-in-out 1.4s infinite' }}>
        <circle cx="70" cy="70" r="62" fill={`url(#ink-${gid})`} style={{
          opacity: 0, transformOrigin: '70px 70px',
          animation: 'c888-pop 0.55s cubic-bezier(0.34,1.56,0.64,1) 0s forwards',
        }}/>
        <ellipse cx="50" cy="44" rx="18" ry="9" fill="#fff" fillOpacity="0.12" style={{
          opacity: 0, animation: 'c888-fade 0.4s ease-out 0.45s forwards',
        }}/>
        <circle cx="70" cy="70" r="30" fill={`url(#cream-${gid})`} style={{
          opacity: 0, transformOrigin: '70px 70px',
          animation: 'c888-cream 0.5s cubic-bezier(0.34,1.56,0.64,1) 0.55s forwards',
        }}/>
        <text
          x="70" y="80" textAnchor="middle"
          fontFamily="DM Serif Display, Georgia, serif"
          fontWeight="900" fontSize="23" fill="#17140d" letterSpacing="-0.5"
          style={{ opacity: 0, animation: 'c888-fade 0.4s ease-out 0.9s forwards' }}
        >888</text>
      </g>
    </svg>
  );
}

// CSS keyframes injected via <style> — ids prefixed with c888- so they can't
// collide with global CSS.
const commissionAnimationsCss = `
@keyframes c888-draw {
  0%   { stroke-dashoffset: 260; }
  55%  { stroke-dashoffset: 0; }
  75%  { stroke-dashoffset: 0; }
  100% { stroke-dashoffset: -260; }
}
@keyframes c888-dot {
  0%, 45% { opacity: 0; }
  55%     { opacity: 1; }
  75%     { opacity: 1; }
  100%    { opacity: 0; }
}
@keyframes c888-bloom {
  0%   { r: 5;  fill-opacity: 0.32; }
  80%  { r: 26; fill-opacity: 0;    }
  100% { r: 26; fill-opacity: 0;    }
}
@keyframes c888-pop {
  0%   { opacity: 0; transform: scale(0.6); }
  100% { opacity: 1; transform: scale(1);   }
}
@keyframes c888-cream {
  0%   { opacity: 0; transform: scale(0.2); }
  100% { opacity: 1; transform: scale(1);   }
}
@keyframes c888-fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@keyframes c888-breathe {
  0%, 100% { transform: scale(1);    }
  50%      { transform: scale(1.02); }
}
`;

window.CommissionScreen = CommissionScreen;
