// Main app: persona routing, demo chrome, product frame, tweaks integration

const { useState: appUseState, useEffect: appUseEffect, useRef: appUseRef } = React;

// Per-persona browser-bar URLs
const PERSONA_URLS = {
  lender: 'portal.marinecheckhq.co.uk/lender',
  insurer: 'portal.marinecheckhq.co.uk/insurer',
  broker: 'brokers.marinecheckhq.co.uk',
  marina: 'marina.marinecheckhq.co.uk',
  consumer: 'marinecheckhq.co.uk',
};
window.PERSONA_URLS = PERSONA_URLS;

// ---------- PersonaShell — demo chrome + product frame ----------
const PersonaShell = ({ persona, steps, currentStep, onStep, onBack, hint, injectStyle, children }) => {
  return (
    <div style={{ minHeight: '100vh', background: 'var(--demo-bg)', color: 'var(--demo-fg)' }}>
      {injectStyle && <style>{injectStyle}</style>}

      {/* ───── DEMO CHROME (clearly demo, not the product) ───── */}
      <DemoBar persona={persona} onBack={onBack} />

      <div style={{ maxWidth: 1400, margin: '0 auto', padding: '20px 32px 12px' }}>
        <DemoNarration persona={persona} steps={steps} currentStep={currentStep} onStep={onStep} hint={hint} />
      </div>

      {/* ───── PRODUCT (browser-framed, this is what the user actually sees) ───── */}
      <div style={{ maxWidth: 1400, margin: '0 auto', padding: '0 32px 56px' }}>
        <div style={{
          background: 'var(--paper)',
          borderRadius: 12,
          overflow: 'hidden',
          boxShadow: '0 30px 60px -20px rgba(0,0,0,0.4), 0 8px 20px -10px rgba(0,0,0,0.25)',
          border: '1px solid var(--demo-line)',
        }}>
          <BrowserBar persona={persona} />
          <ProductTopBar persona={persona} />
          {/* In-product progress — so the persona always knows how many steps remain */}
          <ProductProgress steps={steps} currentStep={currentStep} onStep={onStep} />
          <div style={{ background: 'var(--paper)', padding: '24px 28px 40px' }}>
            {children}
          </div>
        </div>
      </div>

      {/* ───── DEMO FOOTER ───── */}
      <div style={{ maxWidth: 1400, margin: '0 auto', padding: '20px 32px 32px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11.5, color: 'var(--demo-fg-3)' }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="sparkle" size={11} color="var(--demo-accent)" />The dark frame is the demo wrapper · everything inside the browser window is the product</span>
        <span className="mono">MarineCheck Demo · v0.4</span>
      </div>
    </div>
  );
};

// ---------- In-product progress bar ----------
const ProductProgress = ({ steps, currentStep, onStep }) => {
  const total = steps.length;
  const isDone = currentStep >= total;
  const safeCurrent = Math.min(currentStep, total - 1);
  const remaining = Math.max(0, total - currentStep - 1);

  return (
    <div style={{
      background: 'var(--paper-2)',
      borderBottom: '1px solid var(--line)',
      padding: '12px 24px',
      display: 'flex', alignItems: 'center', gap: 20,
    }}>
      {/* Counter */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 0 }}>
        <span style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500 }}>Step</span>
        <span className="mono" style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>
          {isDone ? String(total).padStart(2, '0') : String(safeCurrent + 1).padStart(2, '0')}
          <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}> / {String(total).padStart(2, '0')}</span>
        </span>
        <span style={{ fontSize: 13, color: 'var(--ink-2)', marginLeft: 8 }}>· {isDone ? 'Completed' : steps[safeCurrent]}</span>
      </div>

      {/* Pips */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
        {steps.map((s, i) => {
          const done = isDone ? true : i < safeCurrent;
          const curr = !isDone && i === safeCurrent;
          const clickable = onStep && (isDone || i <= safeCurrent);
          return (
            <button
              key={i}
              type="button"
              onClick={() => clickable && onStep(i)}
              title={`Step ${i + 1}: ${s}`}
              style={{
                flex: 1,
                height: 4,
                borderRadius: 2,
                background: done ? 'var(--clean)' : curr ? 'var(--accent)' : 'var(--line)',
                border: 'none',
                cursor: clickable ? 'pointer' : 'default',
                padding: 0,
                transition: 'background .2s',
                position: 'relative',
              }}
            >
              {curr && (
                <span style={{
                  position: 'absolute', top: -3, left: 0, right: 0, height: 10,
                  borderRadius: 5,
                  background: 'var(--accent)',
                  opacity: 0.25,
                  animation: 'pulseDot 1.6s ease-in-out infinite',
                }} />
              )}
            </button>
          );
        })}
      </div>

      {/* Remaining / done */}
      <div style={{ fontSize: 12, color: 'var(--ink-3)', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 6 }}>
        {isDone ? (
          <><Icon name="check" size={12} color="var(--clean)" strokeWidth={2.2} /><span style={{ color: 'var(--clean)', fontWeight: 500 }}>Task complete</span></>
        ) : remaining === 0 ? (
          <span style={{ color: 'var(--accent)', fontWeight: 500 }}>Final step</span>
        ) : (
          <>{remaining} {remaining === 1 ? 'step' : 'steps'} remaining</>
        )}
      </div>
    </div>
  );
};

// ---------- Demo bar (dark) ----------
const DemoBar = ({ persona, onBack }) => {
  const [open, setOpen] = appUseState(false);
  const ref = appUseRef(null);
  appUseEffect(() => {
    const click = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', click);
    return () => document.removeEventListener('mousedown', click);
  }, []);

  return (
    <div style={{
      borderBottom: '1px solid var(--demo-line)',
      padding: '10px 32px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: 'var(--demo-bg-2)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'var(--demo-fg)' }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--demo-accent)' }} />
          <span style={{ fontSize: 12.5, fontWeight: 500, letterSpacing: '0.01em' }}>MarineCheck · Demo prototype</span>
        </span>
        <span style={{ color: 'var(--demo-fg-3)', fontSize: 12 }}>·</span>
        <span style={{ fontSize: 11.5, color: 'var(--demo-fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }} className="mono">5 user journeys</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <button
          type="button"
          onClick={onBack}
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '5px 10px', borderRadius: 6,
            border: '1px solid var(--demo-line)',
            background: 'transparent', color: 'var(--demo-fg-2)',
            cursor: 'pointer', fontSize: 12,
          }}
        >
          <Icon name="map" size={12} color="var(--demo-fg-2)" />
          All personas
        </button>
        <div ref={ref} style={{ position: 'relative' }}>
          <button
            type="button"
            onClick={() => setOpen(o => !o)}
            style={{
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '5px 10px', borderRadius: 6,
              border: '1px solid var(--demo-line)',
              background: 'oklch(0.27 0.012 250)', color: 'var(--demo-fg)',
              cursor: 'pointer', fontSize: 12, fontWeight: 500,
            }}
          >
            <Icon name={{ lender: 'pound', insurer: 'shield', broker: 'doc', marina: 'scan', consumer: 'user' }[persona.id]} size={12} color="var(--demo-accent)" />
            Viewing as: {persona.label}
            <Icon name="chevronDown" size={11} color="var(--demo-fg-3)" />
          </button>
          {open && (
            <div style={{
              position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 60,
              minWidth: 280, padding: 4,
              background: 'oklch(0.24 0.012 250)',
              border: '1px solid var(--demo-line)',
              borderRadius: 8,
              boxShadow: '0 20px 40px -10px rgba(0,0,0,0.4)',
            }}>
              <div style={{ padding: '8px 10px', fontSize: 10.5, color: 'var(--demo-fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em', borderBottom: '1px solid var(--demo-line)' }}>
                Switch persona
              </div>
              {PERSONAS.map(p => (
                <button
                  key={p.id}
                  type="button"
                  onClick={() => { setOpen(false); window.__switchPersona && window.__switchPersona(p.id); }}
                  style={{
                    width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                    padding: '8px 10px',
                    background: p.id === persona.id ? 'oklch(0.3 0.04 245)' : 'transparent',
                    border: 'none', borderRadius: 5,
                    textAlign: 'left', cursor: 'pointer', color: 'var(--demo-fg)',
                  }}
                  onMouseEnter={(e) => { if (p.id !== persona.id) e.currentTarget.style.background = 'oklch(0.27 0.012 250)'; }}
                  onMouseLeave={(e) => { if (p.id !== persona.id) e.currentTarget.style.background = 'transparent'; }}
                >
                  <div style={{
                    width: 26, height: 26, borderRadius: 6,
                    background: 'oklch(0.3 0.012 250)', color: 'var(--demo-accent)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Icon name={{ lender: 'pound', insurer: 'shield', broker: 'doc', marina: 'scan', consumer: 'user' }[p.id]} size={13} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{p.label}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--demo-fg-3)' }}>{p.org}</div>
                  </div>
                  {p.id === persona.id && <Icon name="check" color="var(--demo-accent)" size={14} strokeWidth={2.2} />}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ---------- Demo narration block ----------
const DemoNarration = ({ persona, steps, currentStep, onStep, hint }) => {
  const personaIdx = PERSONAS.findIndex(p => p.id === persona.id);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 24 }}>
        <div style={{ minWidth: 0 }}>
          <div className="mono" style={{ fontSize: 10.5, color: 'var(--demo-fg-3)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 6 }}>
            Journey {String(personaIdx + 1).padStart(2, '0')} · Narration
          </div>
          <div style={{ fontSize: 17, fontWeight: 500, color: 'var(--demo-fg)', maxWidth: 880, letterSpacing: '-0.01em', lineHeight: 1.4, textWrap: 'balance' }}>
            {persona.objective}
          </div>
        </div>
        {hint && (
          <div style={{ maxWidth: 360, fontSize: 11.5, color: 'var(--demo-fg-2)', padding: '8px 12px', background: 'oklch(0.24 0.012 250)', border: '1px solid var(--demo-line)', borderRadius: 8, display: 'flex', alignItems: 'flex-start', gap: 8 }}>
            <Icon name="sparkle" size={13} color="var(--demo-accent)" />
            <span>{hint}</span>
          </div>
        )}
      </div>

      {/* Step strip styled for dark chrome */}
      <div style={{
        display: 'flex', alignItems: 'stretch',
        background: 'oklch(0.24 0.012 250)',
        border: '1px solid var(--demo-line)',
        borderRadius: 8,
        overflow: 'hidden',
      }}>
        {steps.map((s, i) => {
          const isDone = i < currentStep;
          const isCurrent = i === currentStep;
          return (
            <div
              key={i}
              onClick={() => onStep && i <= currentStep && onStep(i)}
              style={{
                flex: 1, padding: '10px 14px',
                borderRight: i < steps.length - 1 ? '1px solid var(--demo-line)' : 'none',
                cursor: onStep && i <= currentStep ? 'pointer' : 'default',
                background: isCurrent ? 'oklch(0.32 0.05 245)' : 'transparent',
                display: 'flex', flexDirection: 'column', gap: 2,
              }}
            >
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.06em', color: isDone ? 'var(--clean)' : isCurrent ? 'var(--demo-accent)' : 'var(--demo-fg-3)' }}>
                STEP {String(i + 1).padStart(2, '0')} {isDone ? '· DONE' : isCurrent ? '· LIVE' : ''}
              </div>
              <div style={{ fontSize: 12.5, fontWeight: 500, color: isCurrent ? 'white' : isDone ? 'var(--demo-fg)' : 'var(--demo-fg-3)' }}>
                {s}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ---------- Browser bar (window chrome on the product card) ----------
const BrowserBar = ({ persona }) => (
  <div style={{
    background: 'oklch(0.96 0.005 250)',
    borderBottom: '1px solid var(--line)',
    padding: '8px 14px',
    display: 'flex', alignItems: 'center', gap: 12,
  }}>
    <span style={{ display: 'flex', gap: 6 }}>
      <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#ff5f57' }} />
      <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#febc2e' }} />
      <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#28c840' }} />
    </span>
    <div className="mono" style={{
      flex: 1, maxWidth: 480, margin: '0 auto',
      textAlign: 'center', fontSize: 11.5,
      color: 'var(--ink-3)',
      background: 'white',
      border: '1px solid var(--line)', borderRadius: 5,
      padding: '3px 12px',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    }}>
      <Icon name="lock" size={10} color="var(--clean)" />
      {PERSONA_URLS[persona.id]}
    </div>
    <div style={{ width: 47 }} /> {/* spacer to keep URL centered */}
  </div>
);

// ---------- Product top bar (this IS the product, not demo chrome) ----------
const ProductTopBar = ({ persona }) => (
  <div style={{
    borderBottom: '1px solid var(--line)',
    background: 'var(--surface)',
    padding: '10px 24px',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <MCLogo size="sm" />
      <span style={{ color: 'var(--line-2)' }}>/</span>
      <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{persona.org}</span>
    </div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, fontSize: 12, color: 'var(--ink-3)' }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="user" size={13} color="var(--ink-3)" />
        {persona.user}
      </span>
      <span className="pill pill-info" style={{ fontSize: 10.5 }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--accent)', animation: 'pulseDot 2s ease-in-out infinite' }} />
        SSO · 2FA
      </span>
    </div>
  </div>
);

// ---------- Tweaks defaults (persisted) ----------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lenderLayout": "split",
  "insurerLayout": "inbox",
  "startPersona": "picker"
}/*EDITMODE-END*/;

// ---------- App root ----------
const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [persona, setPersona] = appUseState(null); // null means: persona picker
  const [pickerKey, setPickerKey] = appUseState(0);

  // Expose switcher globally for the top-bar dropdown
  appUseEffect(() => {
    window.__switchPersona = (id) => setPersona(id);
  }, []);

  const goPicker = () => { setPersona(null); setPickerKey(k => k + 1); };

  return (
    <>
      {!persona && <PersonaPicker key={pickerKey} onPick={setPersona} />}
      {persona === 'lender' && <LenderJourney layout={t.lenderLayout} onBack={goPicker} key={'lender-' + t.lenderLayout} />}
      {persona === 'insurer' && <InsurerJourney layout={t.insurerLayout} onBack={goPicker} key={'insurer-' + t.insurerLayout} />}
      {persona === 'broker' && <BrokerJourney onBack={goPicker} />}
      {persona === 'marina' && <MarinaJourney onBack={goPicker} />}
      {persona === 'consumer' && <ConsumerJourney onBack={goPicker} />}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Persona">
          <TweakSelect
            label="Workspace"
            value={persona || 'picker'}
            onChange={(v) => setPersona(v === 'picker' ? null : v)}
            options={[
              { value: 'picker', label: '← Persona picker' },
              { value: 'lender', label: 'Finance / Lender' },
              { value: 'insurer', label: 'Insurance / MGA' },
              { value: 'broker', label: 'Broker / Dealer' },
              { value: 'marina', label: 'Marina' },
              { value: 'consumer', label: 'Boat buyer' },
            ]}
          />
        </TweakSection>

        <TweakSection label="Hero dashboard layouts">
          <TweakRadio
            label="Lender"
            value={t.lenderLayout}
            onChange={(v) => setTweak('lenderLayout', v)}
            options={[
              { value: 'split', label: 'Split' },
              { value: 'workflow', label: 'Workflow' },
            ]}
          />
          <TweakRadio
            label="Insurer"
            value={t.insurerLayout}
            onChange={(v) => setTweak('insurerLayout', v)}
            options={[
              { value: 'inbox', label: 'Inbox' },
              { value: 'workspace', label: 'Workspace' },
            ]}
          />
        </TweakSection>

        <TweakSection label="Demo notes">
          <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5, padding: '4px 0' }}>
            12 mock vessels seeded. Flags:<br />
            · Northumbria — outstanding charge<br />
            · Kestrel — duplicate cover<br />
            · Black Mamba — stolen alert
          </div>
        </TweakSection>
      </TweaksPanel>
    </>
  );
};

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