// app.jsx — main App + greeting (step 1) + stepper + Tweaks

const { useState, useEffect } = React;

const STEPS = [
  { id: 'greet',    label: 'Start' },
  { id: 'picker',   label: 'Document type' },
  { id: 'form',     label: 'Details' },
  { id: 'draft',    label: 'Review draft' },
  { id: 'deliver',  label: 'Deliver' },
];

// ─── Auth helpers (shared password) ─────────────────────────────────────
// The backend protects /api/generate, /api/chat, /api/finalize behind a
// shared-password Bearer-token check. We store the password in localStorage
// after a successful login and include it on every fetch.

window.authedFetch = function(url, opts = {}) {
  const pw = localStorage.getItem('ceg_app_password') || '';
  return fetch(url, {
    ...opts,
    headers: {
      ...(opts.headers || {}),
      ...(pw ? { 'Authorization': 'Bearer ' + pw } : {}),
    },
  });
};

function LoginGate({ onAuth }) {
  const [pw, setPw] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => { if (window.lucide) window.lucide.createIcons(); }, [busy, error]);

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!pw.trim()) return;
    setBusy(true); setError(null);
    try {
      const res = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Authorization': 'Bearer ' + pw, 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });
      if (res.ok) {
        localStorage.setItem('ceg_app_password', pw);
        onAuth();
      } else {
        setError('Wrong password.');
      }
    } catch (e) {
      setError('Could not reach the server. Try again in a moment.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--ink-50, #f7f8fa)',
      fontFamily: 'var(--font-body)',
    }}>
      <form onSubmit={submit} style={{
        background: '#fff',
        padding: '40px 48px',
        borderRadius: 'var(--radius-lg, 12px)',
        boxShadow: '0 12px 40px -8px rgba(0,0,0,0.1), 0 4px 12px -4px rgba(0,0,0,0.06)',
        width: 380, maxWidth: '92vw',
        textAlign: 'center',
      }}>
        <img src="assets/logos/ceg-square-nobg.png" alt="CEG" style={{width: 56, height: 56, marginBottom: 14}}/>
        <h2 style={{margin: '0 0 6px', fontSize: 22, color: 'var(--ceg-navy)', fontWeight: 700}}>
          CEG Boilerplate
        </h2>
        <p style={{margin: '0 0 28px', color: 'var(--ink-500)', fontSize: 13}}>
          Internal access only. Enter the team password to continue.
        </p>
        <input
          type="password"
          value={pw}
          autoFocus
          placeholder="Password"
          onChange={e => setPw(e.target.value)}
          disabled={busy}
          style={{
            width: '100%', padding: '12px 14px',
            fontSize: 15, fontFamily: 'inherit',
            border: '1px solid var(--border-strong, #d4d8e0)',
            borderRadius: 8, marginBottom: 14, boxSizing: 'border-box',
          }}
        />
        {error && (
          <div style={{
            padding: '10px 12px', marginBottom: 14,
            background: 'rgba(220, 38, 38, 0.08)',
            border: '1px solid rgba(220, 38, 38, 0.25)',
            borderRadius: 8, color: '#991B1B', fontSize: 13,
          }}>
            {error}
          </div>
        )}
        <button type="submit" disabled={busy || !pw.trim()} className="btn btn-accent" style={{
          width: '100%', padding: '12px 14px', fontSize: 15,
        }}>
          {busy ? 'Checking…' : 'Continue →'}
        </button>
      </form>
    </div>
  );
}

// ─── AuthBoot — checks on mount whether a password is required and whether
// any saved password still works. Renders <LoginGate> if not authed.
function AuthBoot({ children }) {
  // null = checking; true = ok; false = needs login
  const [authed, setAuthed] = useState(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const pw = localStorage.getItem('ceg_app_password') || '';
        const res = await fetch('/api/health', {
          headers: pw ? { 'Authorization': 'Bearer ' + pw } : {},
        });
        if (cancelled) return;
        if (!res.ok) {
          setAuthed(false);
          return;
        }
        const data = await res.json();
        // If no password is configured server-side (local dev), skip the gate.
        // Otherwise require a valid Authorization header.
        if (!data.passwordSet) {
          setAuthed(true);
        } else {
          setAuthed(!!data.authorized);
        }
      } catch {
        if (!cancelled) setAuthed(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  if (authed === null) {
    // Quick neutral splash while we check — avoids a flash of LoginGate
    // for already-authed users.
    return (
      <div style={{
        minHeight: '100vh', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: 'var(--ink-50, #f7f8fa)',
      }}>
        <div style={{color: 'var(--ink-400)', fontSize: 13}}>Loading…</div>
      </div>
    );
  }
  if (!authed) return <LoginGate onAuth={() => setAuthed(true)} />;
  return children;
}

function App() {
  const [t, setTweak] = window.useTweaks(window.TWEAK_DEFAULTS);
  const [step, setStep] = useState('greet');
  const [docId, setDocId] = useState(null);
  const [values, setValues] = useState(null);
  const [notes, setNotes] = useState('');

  useEffect(() => { if (window.lucide) window.lucide.createIcons(); }, [step, t.pickerStyle, t.density, t.navyNav]);
  useEffect(() => { document.body.className = `density-${t.density || 'regular'}`; }, [t.density]);

  const stepIdx = STEPS.findIndex(s => s.id === step);

  const goto = (id) => setStep(id);
  const resumeDraft = (recent) => {
    setDocId(recent.docId);
    setValues(window.DEMO_VALUES[recent.docId] || {});
    setStep('form');
  };
  const startFresh = () => setStep('picker');

  return (
    <div className="app-shell">
      <AppNav navy={t.navyNav} />
      <StepperBar steps={STEPS} idx={stepIdx} onClick={(id, i) => { if (i <= stepIdx) setStep(id); }} />

      <div className="app-main">
        {step === 'greet' && (
          <GreetingStep
            onStartFresh={startFresh}
            onResume={resumeDraft}
            onPickQuick={(id) => { setDocId(id); setValues(null); setStep('form'); }}
          />
        )}
        {step === 'picker' && (
          <window.DocPickerStep
            pickerStyle={t.pickerStyle}
            onSelect={(id) => { setDocId(id); setValues(null); setStep('form'); }}
            onBack={() => setStep('greet')}
          />
        )}
        {step === 'form' && docId && (
          <window.FormStep
            docId={docId}
            initialValues={values}
            showCompleteness={t.showCompleteness}
            showCoaching={t.showCoaching}
            onBack={() => setStep('picker')}
            onSubmit={(v, n) => { setValues(v); setNotes(n); setStep('draft'); }}
          />
        )}
        {step === 'draft' && docId && (
          <window.DraftStep
            docId={docId}
            values={values || {}}
            notes={notes}
            onBack={() => setStep('form')}
            onFinalize={() => setStep('deliver')}
          />
        )}
        {step === 'deliver' && docId && (
          <window.DeliveryStep
            docId={docId}
            values={values || {}}
            onBack={() => setStep('draft')}
            onStartOver={() => { setDocId(null); setValues(null); setNotes(''); setStep('greet'); }}
          />
        )}
      </div>

      <TweaksUI t={t} setTweak={setTweak} />
    </div>
  );
}

function AppNav({ navy }) {
  return (
    <nav className={`app-nav ${navy ? '' : 'light'}`}>
      <div className="brand">
        <img src="assets/logos/ceg-square-nobg.png" alt="CEG"/>
        <div className="brand-text">
          <span className="brand-name">Commercial Equities Group</span>
          <span className="brand-sub">Boilerplate</span>
        </div>
      </div>
      <span className="product-tag">Document Builder</span>
      <div className="nav-links">
        <span className="nav-link active">Drafts</span>
        <span className="nav-link">Activity</span>
      </div>
      <div className="nav-right">
        <div className="icon-btn" title="Notifications"><i data-lucide="bell" style={{width:16, height:16, strokeWidth:1.75}}></i></div>
        <div style={{width: 1, height: 24, background: 'rgba(255,255,255,0.10)'}}></div>
        <div className="avatar" title="Brian Potratz">BP</div>
      </div>
    </nav>
  );
}

function StepperBar({ steps, idx, onClick }) {
  return (
    <div className="stepper-bar">
      <div className="stepper">
        {steps.map((s, i) => (
          <React.Fragment key={s.id}>
            <div
              className={`step ${i < idx ? 'done' : ''} ${i === idx ? 'active' : ''}`}
              onClick={() => onClick(s.id, i)}
              style={{opacity: i > idx ? 0.55 : 1, cursor: i <= idx ? 'pointer' : 'default'}}
            >
              <div className="dot">
                {i < idx ? <i data-lucide="check" style={{width:11, height:11, strokeWidth:3}}></i> : (i + 1).toString().padStart(2,'0')}
              </div>
              <div className="label">{s.label}</div>
            </div>
            {i < steps.length - 1 && <div className="step"><div className="sep"></div></div>}
          </React.Fragment>
        ))}
      </div>
      <div style={{display: 'flex', alignItems: 'center', gap: 12, color: 'var(--ink-500)', fontSize: 12}}>
        <i data-lucide="shield-check" style={{width:13, height:13, color:'var(--success)'}}></i>
        Approved language only
        <span style={{width:1, height:14, background:'var(--border-subtle)'}}></span>
        <i data-lucide="users" style={{width:13, height:13}}></i>
        Routes to Halie for review
      </div>
    </div>
  );
}

// ─── Step 1: Greeting ─────────────────────────────────────────────────────
function GreetingStep({ onStartFresh, onResume, onPickQuick }) {
  useEffect(() => { if (window.lucide) window.lucide.createIcons(); }, []);
  const recent = window.RECENT_DRAFTS;
  const hour = new Date().getHours();
  const tod = hour < 12 ? 'morning' : hour < 18 ? 'afternoon' : 'evening';

  return (
    <div className="canvas-pad">
      <div className="hero-greet">
        <div className="greet-panel fade-in">
          <div className="eyebrow-sm">CEG · Boilerplate</div>
          <h1>Good {tod}, Brian.</h1>
          <p className="lead" style={{marginBottom: 28}}>
            Pick a CEG-approved template, fill in the deal, and we’ll draft it for you.
          </p>
          <div className="greet-cta-row">
            <button className="btn btn-accent btn-lg" onClick={onStartFresh}>
              <i data-lucide="plus"></i> Start a new document <i data-lucide="arrow-right"></i>
            </button>
          </div>
        </div>

        <div className="recent-panel fade-in-d2">
          <div className="head">
            <div>
              <h3>Your recent drafts</h3>
            </div>
            <button className="btn btn-text btn-sm">View all <i data-lucide="arrow-right"></i></button>
          </div>
          <div className="recent-list">
            {recent.map(r => {
              const doc = window.DOC_BY_ID[r.docId];
              return (
                <div key={r.id} className="recent-item" onClick={() => onResume(r)}>
                  <div className="doc-icon"><i data-lucide={doc?.icon || 'file-text'}></i></div>
                  <div className="title-wrap">
                    <div className="title">{r.title}</div>
                    <div className="sub">{r.sub}</div>
                  </div>
                  <div className="right">
                    <span className={`chip ${r.status}`}>
                      {r.status !== 'sent' && <span className="dot"></span>}
                      {r.statusLabel}
                    </span>
                    <span className="meta">{r.updated}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      <div style={{height: 40}}></div>
    </div>
  );
}

// ─── Tweaks ───────────────────────────────────────────────────────────────
function TweaksUI({ t, setTweak }) {
  return (
    <window.TweaksPanel>
      <window.TweakSection label="Document picker"/>
      <window.TweakRadio
        label="Layout"
        value={t.pickerStyle}
        options={['grid', 'featured', 'list']}
        onChange={v => setTweak('pickerStyle', v)}
      />

      <window.TweakSection label="Form guardrails"/>
      <window.TweakToggle label="Completeness meter" value={t.showCompleteness} onChange={v => setTweak('showCompleteness', v)} />
      <window.TweakToggle label="Coaching tips" value={t.showCoaching} onChange={v => setTweak('showCoaching', v)} />

      <window.TweakSection label="Appearance"/>
      <window.TweakRadio
        label="Density"
        value={t.density}
        options={['compact','regular','comfy']}
        onChange={v => setTweak('density', v)}
      />
      <window.TweakToggle label="Navy navigation" value={t.navyNav} onChange={v => setTweak('navyNav', v)} />
    </window.TweaksPanel>
  );
}

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