// Opalus — Investment wizard (INV-15→18) + reflection period (19), withdraw (20), confirmed & sign (21)
const IV = window.OpalusDesignSystem_1dce4b;
const FOUR_DAYS = 4 * 24 * 60 * 60 * 1000;

function fmtDateTime(ms) {
  const d = new Date(ms);
  return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) + ', ' +
    d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
}
function remainingCap(p) { return Math.max(0, p.target - p.raised); }

/* ============================================================ INVEST WIZARD ============================================================ */
function InvestScreen() {
  const { state, update, go } = window.useOpalus();
  const { Button, Card } = IV;
  const inv = state.investor;
  const p = window.OPALUS_PROJECTS.find((x) => x.id === state.route.params.id) || window.OPALUS_PROJECTS[0];
  const soph = inv.category === 'sophisticated';
  const cap = window.individualCap(inv);
  const lossCap = inv.lossSim?.capacity || null;
  const prior = state.holdings.filter((h) => h.projectId === p.id).reduce((n, h) => n + h.invested, 0);

  const [amount, setAmount] = useState(p.min);
  const [scr, setScr] = useState('amount');     // amount | art217 | capacity | kiis | review
  const [art217Ack, setArt217Ack] = useState(false);
  const [art217Ans, setArt217Ans] = useState({});
  const [capAck, setCapAck] = useState(false);
  const [kiisAck, setKiisAck] = useState(false);
  const [kiisLang, setKiisLang] = useState('en');

  const remaining = remainingCap(p);
  const overCap = !soph && amount > cap;                       // triggers Art 21(7)
  const overLoss = !soph && lossCap != null && amount > lossCap * 0.10; // triggers loss-capacity warning

  // ---- amount-step validation (INV-15) ----
  const belowMin = amount < p.min;
  const aboveCapacity = amount > remaining;
  const insufficient = amount > state.wallet.balance;
  const amountError = belowMin ? `The minimum for this project is ${window.eur(p.min)}.`
    : aboveCapacity ? `Only ${window.eur(remaining)} remains available in this project. Enter that amount or less.`
    : null;

  // dynamic step list for the stepper
  const flow = ['amount', ...(overCap ? ['art217'] : []), ...(overLoss ? ['capacity'] : []), 'kiis', 'review'];
  const labels = { amount: 'Amount', art217: 'Risk check', capacity: 'Loss capacity', kiis: 'KIIS', review: 'Review' };
  const stepIdx = Math.max(0, flow.indexOf(scr));
  const goNext = () => { const i = flow.indexOf(scr); if (i < flow.length - 1) { setScr(flow[i + 1]); window.scrollTo(0, 0); } };
  const goPrev = () => { const i = flow.indexOf(scr); if (i > 0) { setScr(flow[i - 1]); window.scrollTo(0, 0); } else go('project', { id: p.id }); };

  const submit = () => {
    const now = Date.now();
    update((s) => {
      if (soph) {
        s.holdings.unshift({ id: 'h' + now, projectId: p.id, invested: amount, value: amount, roiPct: 0, yieldPct: (p.returnLow + p.returnHigh) / 2, status: 'awaiting-signature', kiisVersion: 3, committedAt: now, coolingEnds: 0 });
        s.wallet.balance = Math.max(0, s.wallet.balance - amount);
        s.wallet.transactions.unshift({ id: 'tx' + now, type: 'Investment released', label: `Investment released · ${p.title}`, amount: -amount, date: 'Today', kind: 'out', status: 'Completed' });
      } else {
        s.holdings.unshift({ id: 'h' + now, projectId: p.id, invested: amount, value: amount, roiPct: 0, yieldPct: (p.returnLow + p.returnHigh) / 2, status: 'offer', kiisVersion: 3, committedAt: now, coolingEnds: now + FOUR_DAYS });
        s.wallet.balance = Math.max(0, s.wallet.balance - amount);
        s.wallet.transactions.unshift({ id: 'tx' + now, type: 'Investment reserved', label: `Investment reserved · ${p.title}`, amount: -amount, date: 'Today', kind: 'out', status: 'Completed' });
      }
    });
    go(soph ? 'confirmed' : 'reflection', { hid: 'h' + now });
  };

  return (
    <div className="opx-container opx-fade" style={{ maxWidth: 960 }}>
      <button type="button" onClick={goPrev} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-body)', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', marginBottom: 20, padding: 0 }}>
        <IV.IconlyRegularOutlineArrowLeft style={{ width: 18, height: 18 }} /> {scr === 'amount' ? `Back to ${p.title}` : 'Back'}
      </button>
      <div style={{ padding: '0 8px 28px', maxWidth: 640, margin: '0 auto' }}>
        <window.Stepper steps={flow.map((k) => labels[k])} current={stepIdx} />
      </div>

      <div className="opx-fade" key={scr}>
        {scr === 'amount' && (
          <div className="opx-detail opx-invest-cols" style={{ gridTemplateColumns: '1.4fr 1fr', gap: 24, alignItems: 'start' }}>
            <Card padding="lg" radius="xl" shadow="sm" style={{ padding: 32 }}>
              <window.Eyebrow>Step 1 · Your offer</window.Eyebrow>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, color: 'var(--ink)', margin: '8px 0 20px' }}>How much would you like to invest?</h2>
              <window.Field label="Amount (EUR)">
                <input className="opx-amount" type="number" min={p.min} step={500} value={amount} onChange={(e) => setAmount(Math.max(0, +e.target.value || 0))} />
              </window.Field>
              <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
                {[1000, 2500, 5000, 10000].map((c) => <button key={c} type="button" onClick={() => setAmount(c)} style={{ cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, padding: '8px 14px', borderRadius: 'var(--radius-pill)', border: `1px solid ${amount === c ? 'var(--bronze-500)' : 'var(--border-subtle)'}`, background: amount === c ? 'var(--cream-100)' : '#fff', color: amount === c ? 'var(--bronze-700)' : 'var(--text-body)' }}>{window.eur(c)}</button>)}
              </div>

              {amountError && <div style={{ marginTop: 16 }}><window.Note tone="danger" icon={<span style={{ fontWeight: 700 }}>!</span>}>{amountError}</window.Note></div>}
              {!amountError && insufficient && (
                <div style={{ marginTop: 16 }}>
                  <window.Note tone="info" title="Add funds to invest this amount">Your available balance is {window.eurC(state.wallet.balance)}. <span className="opx-link" onClick={() => go('wallet', { deposit: true })}>Deposit funds →</span></window.Note>
                </div>
              )}
              {!amountError && !insufficient && overCap && (
                <div style={{ marginTop: 16 }}><window.Note tone="warn" title="A risk check applies" icon={<span style={{ fontWeight: 700 }}>!</span>}>This exceeds the greater of €1,000 or 5% of your net worth ({window.eur(cap)}). You'll be asked to confirm you understand the risks before continuing.</window.Note></div>
              )}

              <Button variant="primary" style={{ marginTop: 22 }} disabled={!!amountError || insufficient} onClick={goNext} trailingIcon={<IV.IconlyRegularLightArrowRight style={{ width: 18, height: 18 }} />}>Continue</Button>
            </Card>

            <Card padding="lg" radius="xl" shadow="sm" cream style={{ padding: 26 }}>
              <img src={p.image} alt="" style={{ width: '100%', height: 130, objectFit: 'cover', borderRadius: 'var(--radius-md)' }} />
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-micro)', fontWeight: 600, letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase', color: 'var(--bronze-700)', margin: '14px 0 2px' }}>Project</div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17, color: 'var(--ink)', margin: '0 0 4px' }}>{p.title}</h3>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-muted)', marginBottom: 12 }}>{p.location}</div>
              {[['Projected return', `${window.pct(p.returnLow)}–${window.pct(p.returnHigh)}`], ['Term', `${p.term} months`], ...(prior ? [['Your previous investment in this project', window.eur(prior)]] : [])].map(([l, v]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '9px 0', borderTop: '1px solid var(--bronze-300)', fontFamily: 'var(--font-body)', fontSize: 13 }}>
                  <span style={{ color: 'var(--text-body)' }}>{l}</span><span style={{ fontWeight: 600, color: 'var(--ink)', textAlign: 'right' }}>{v}</span>
                </div>
              ))}
            </Card>
          </div>
        )}

        {scr === 'art217' && <Art217Step amount={amount} ans={art217Ans} setAns={setArt217Ans} ack={art217Ack} setAck={setArt217Ack} onNext={goNext} onBack={goPrev} />}
        {scr === 'capacity' && <CapacityStep amount={amount} lossCap={lossCap} date={inv.lossSim?.date} ack={capAck} setAck={setCapAck} onNext={goNext} onBack={goPrev} go={go} />}
        {scr === 'kiis' && <KiisStep p={p} amount={amount} ack={kiisAck} setAck={setKiisAck} lang={kiisLang} setLang={setKiisLang} onNext={goNext} onBack={goPrev} />}
        {scr === 'review' && <ReviewStep p={p} amount={amount} soph={soph} onSubmit={submit} onBack={goPrev} />}
      </div>
    </div>
  );
}

/* ---------- INV-16 · Step 2a — Large-investment warning (Art 21(7)) ---------- */
function Art217Step({ amount, ans, setAns, ack, setAck, onNext, onBack }) {
  const { Button, Card } = IV;
  const Q = window.ART21_7_QUESTIONS;
  const allAnswered = Q.every((_, i) => ans[i] !== undefined);
  return (
    <Card padding="lg" radius="xl" shadow="sm" style={{ padding: 36, maxWidth: 720, margin: '0 auto' }}>
      <window.Eyebrow>Step 2 · Risk check</window.Eyebrow>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, color: 'var(--ink)', margin: '8px 0 16px' }}>Before you continue</h2>
      <div style={{ background: 'var(--warn-50)', border: '1px solid #e7c98a', borderRadius: 'var(--radius-lg)', padding: '18px 20px', marginBottom: 22 }}>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.6, color: 'var(--text-strong)' }}>{window.OPALUS_COPY.art21_7(window.eur(amount))}</div>
      </div>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', color: 'var(--text-body)', margin: '0 0 18px' }}>Before continuing, confirm you understand what this means. Answer the three questions below.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {Q.map((item, i) => {
          const picked = ans[i];
          const wrong = picked !== undefined && picked !== item.correct;
          return (
            <div key={i}>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', fontWeight: 600, color: 'var(--ink)', marginBottom: 9 }}>{i + 1}. {item.q}</div>
              <div style={{ display: 'flex', gap: 10 }}>
                {item.opts.map((opt, oi) => {
                  const sel = picked === oi;
                  return (
                    <button type="button" key={oi} onClick={() => setAns({ ...ans, [i]: oi })} style={{ flex: 1, cursor: 'pointer', padding: '11px 14px', borderRadius: 'var(--radius-md)', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, border: `1.5px solid ${sel ? 'var(--bronze-500)' : 'var(--border-subtle)'}`, background: sel ? 'var(--cream-100)' : '#fff', color: sel ? 'var(--bronze-700)' : 'var(--text-body)' }}>{opt}</button>
                  );
                })}
              </div>
              {wrong && <div style={{ marginTop: 9, fontFamily: 'var(--font-body)', fontSize: 12.5, lineHeight: 1.5, color: 'var(--danger-600)', display: 'flex', gap: 7 }}><span style={{ fontWeight: 700 }}>!</span>{item.explain}</div>}
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--border-faint)' }}>
        <window.AckBox checked={ack} onChange={setAck}>I have read this warning and understand the risks.</window.AckBox>
      </div>
      <div style={{ display: 'flex', gap: 12, marginTop: 22 }}>
        <Button variant="primary" disabled={!allAnswered || !ack} onClick={onNext} trailingIcon={<IV.IconlyRegularLightArrowRight style={{ width: 18, height: 18 }} />}>Continue</Button>
        <Button variant="ghost" onClick={onBack}>Back</Button>
      </div>
    </Card>
  );
}

/* ---------- INV-17 · Step 2b — Loss-capacity warning ---------- */
function CapacityStep({ amount, lossCap, date, ack, setAck, onNext, onBack, go }) {
  const { Button, Card } = IV;
  return (
    <Card padding="lg" radius="xl" shadow="sm" style={{ padding: 36, maxWidth: 680, margin: '0 auto' }}>
      <window.Eyebrow>Step 2 · Loss capacity</window.Eyebrow>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, color: 'var(--ink)', margin: '8px 0 16px' }}>This is above your simulated loss capacity</h2>
      <div style={{ background: 'var(--warn-50)', border: '1px solid #e7c98a', borderRadius: 'var(--radius-lg)', padding: '18px 20px', marginBottom: 18 }}>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.6, color: 'var(--text-strong)' }}>{window.OPALUS_COPY.capacity(window.eur(lossCap || 0), date || '—')}</div>
      </div>
      <div style={{ display: 'flex', gap: 18, marginBottom: 22 }}>
        <span className="opx-link" onClick={() => go('onboarding')} style={{ fontSize: 13 }}>View my simulation</span>
        <span className="opx-link" onClick={() => go('onboarding')} style={{ fontSize: 13 }}>Redo my simulation</span>
      </div>
      <window.AckBox checked={ack} onChange={setAck}>I understand this investment exceeds my simulated loss capacity.</window.AckBox>
      <div style={{ display: 'flex', gap: 12, marginTop: 22 }}>
        <Button variant="primary" disabled={!ack} onClick={onNext} trailingIcon={<IV.IconlyRegularLightArrowRight style={{ width: 18, height: 18 }} />}>Continue</Button>
        <Button variant="ghost" onClick={onBack}>Back</Button>
      </div>
    </Card>
  );
}

/* ---------- INV-18 · Step 3 — KIIS ---------- */
function KiisStep({ p, amount, ack, setAck, lang, setLang, onNext, onBack }) {
  const { Button, Card } = IV;
  const KIIS_VERSION = 3, KIIS_DATE = '14 May 2026';
  const en = [
    ['A', 'Project & issuer', `${p.title}, ${p.location}. ${p.assetType} · ${p.nature}. Raised by a project-specific entity vetted and admitted by the Opalus credit committee. Target raise ${window.compact(p.target)}.`],
    ['B', 'Principal risks', 'Your capital is at risk and you may lose all of it. Returns are targets, not guarantees. The investment is illiquid — there is no secondary market at v1 and you may be unable to exit before the project ends.'],
    ['C', 'Terms of the offer', `${p.instrument} — ${p.equityOffered}% of the SPV's share capital offered. Projected annual return ${window.pct(p.returnLow)}–${window.pct(p.returnHigh)} (not guaranteed). Term ${p.term} months. Returns: ${p.payout}, pro-rata to your shareholding.`],
    ['D', 'Your rights', 'As a non-sophisticated investor you have a 4-calendar-day reflection period, during which you may withdraw your offer without cost and without giving a reason.'],
    ['E', 'Fees & costs', 'You pay no platform, entry or exit fee (0%). The issuer pays Opalus a success fee on capital raised. This does not reduce your headline return.'],
    ['F', 'No approval', 'This information sheet has not been reviewed or approved by the Bank of Lithuania or any competent authority.'],
  ];
  const fr = [
    ['A', 'Projet & émetteur', `${p.title}, ${p.location}. ${p.assetType} · ${p.nature}. Porté par une entité dédiée, vérifiée et admise par le comité de crédit Opalus. Levée cible ${window.compact(p.target)}.`],
    ['B', 'Risques principaux', 'Votre capital est exposé au risque et vous pouvez le perdre en totalité. Les rendements sont des objectifs, non garantis. L’investissement est illiquide — aucun marché secondaire en v1.'],
    ['C', 'Conditions de l’offre', `Actions ordinaires de la SPV du projet — ${p.equityOffered} % du capital social proposé. Rendement annuel projeté ${window.pct(p.returnLow)}–${window.pct(p.returnHigh)} (non garanti). Durée ${p.term} mois. Rendements : dividendes et restitution du capital à la sortie, au prorata de votre participation.`],
    ['D', 'Vos droits', 'En tant qu’investisseur non averti, vous disposez d’un délai de réflexion de 4 jours calendaires, pendant lequel vous pouvez retirer votre offre sans frais et sans motif.'],
    ['E', 'Frais & coûts', 'Vous ne payez aucun frais de plateforme, d’entrée ou de sortie (0 %). L’émetteur verse à Opalus une commission de succès. Cela ne réduit pas votre rendement affiché.'],
    ['F', 'Absence d’approbation', 'Cette fiche n’a pas été examinée ni approuvée par la Banque de Lituanie ni par aucune autorité compétente.'],
  ];
  const parts = lang === 'fr' ? fr : en;
  return (
    <Card padding="lg" radius="xl" shadow="sm" style={{ padding: 0, maxWidth: 740, margin: '0 auto', overflow: 'hidden' }}>
      <div style={{ padding: '26px 32px 18px', borderBottom: '1px solid var(--border-faint)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
          <div>
            <window.Eyebrow>Step 3 · Key Investment Information Sheet</window.Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 22, color: 'var(--ink)', margin: '6px 0 0' }}>Read the document below</h2>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)', marginTop: 4 }}>It's the official description of this project, its risks and its fees. Version {KIIS_VERSION} · {KIIS_DATE}. You are reading a translation — the Lithuanian original is the authoritative version (Art 23(2)).</div>
          </div>
          <button type="button" onClick={() => setLang(lang === 'fr' ? 'en' : 'fr')} style={{ flex: '0 0 auto', cursor: 'pointer', border: '1px solid var(--border-subtle)', background: '#fff', borderRadius: 'var(--radius-pill)', padding: '7px 14px', fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, color: 'var(--bronze-700)' }}>{lang === 'fr' ? 'Read in English' : 'Read in Français'}</button>
        </div>
      </div>
      <div style={{ maxHeight: 340, overflowY: 'auto', padding: '20px 32px' }}>
        {parts.map(([k, t, body]) => (
          <div key={k} style={{ display: 'flex', gap: 16, padding: '14px 0', borderBottom: '1px solid var(--border-faint)' }}>
            <span style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--navy-950)', color: 'var(--bronze-400)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14 }}>{k}</span>
            <div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{t}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-body)', lineHeight: 1.6 }}>{body}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding: '18px 32px 26px', borderTop: '1px solid var(--border-faint)', background: 'var(--surface-inset)' }}>
        <window.AckBox checked={ack} onChange={setAck}>I confirm I have read and understood the Key Investment Information Sheet (version {KIIS_VERSION}, dated {KIIS_DATE}).</window.AckBox>
        <div style={{ display: 'flex', gap: 12, marginTop: 18 }}>
          <Button variant="primary" disabled={!ack} onClick={onNext} trailingIcon={<IV.IconlyRegularLightArrowRight style={{ width: 18, height: 18 }} />}>Continue</Button>
          <Button variant="ghost" onClick={onBack}>Back</Button>
        </div>
      </div>
    </Card>
  );
}

/* ---------- INV-18 · Step 4 — Review ---------- */
function ReviewStep({ p, amount, soph, onSubmit, onBack }) {
  const { Button, Card } = IV;
  const basis = `${window.pct(p.returnLow)}–${window.pct(p.returnHigh)} p.a. (projected)`;
  return (
    <Card padding="lg" radius="xl" shadow="sm" style={{ padding: 36, maxWidth: 680, margin: '0 auto' }}>
      <window.Eyebrow>Step 4 · Review</window.Eyebrow>
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, color: 'var(--ink)', margin: '8px 0 18px' }}>Review your offer</h2>
      <div style={{ border: '1px solid var(--border-faint)', borderRadius: 'var(--radius-lg)', overflow: 'hidden', marginBottom: 22 }}>
        {[['Project', p.title], ['Amount', window.eurC(amount)], ['Fees to you', '€0'], ['Projected return', basis]].map(([k, v], i) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '13px 18px', background: i % 2 ? 'var(--surface-inset)' : '#fff', fontFamily: 'var(--font-body)', fontSize: 13 }}>
            <span style={{ color: 'var(--text-body)' }}>{k}</span><span style={{ fontWeight: 600, color: k === 'Fees to you' ? 'var(--success-600)' : 'var(--ink)', textAlign: 'right' }}>{v}</span>
          </div>
        ))}
      </div>

      {soph ? (
        <div style={{ background: 'var(--info-50)', border: '1px solid var(--info-400)', borderRadius: 'var(--radius-lg)', padding: '16px 18px', marginBottom: 22 }}>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.6, color: 'var(--text-body)' }}>{window.OPALUS_COPY.sophImmediate}</div>
        </div>
      ) : (
        <div style={{ background: 'var(--cream-100)', border: '1px solid var(--bronze-300)', borderRadius: 'var(--radius-lg)', padding: '18px 20px', marginBottom: 22, display: 'flex', gap: 14 }}>
          <IV.IconlyRegularOutlineCalendar style={{ width: 24, height: 24, color: 'var(--bronze-600)', flex: '0 0 auto', marginTop: 1 }} />
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.6, color: 'var(--text-body)' }}>
            After you submit this offer you will have a <b style={{ color: 'var(--ink)' }}>4-calendar-day reflection period</b> during which you may withdraw it <b style={{ color: 'var(--ink)' }}>at no cost, without giving a reason</b>, directly from your dashboard — the same way you are making it now. Your funds stay reserved in your wallet and are only released to the project when the period ends.
          </div>
        </div>
      )}

      {/* Art 10(1) safekeeping / PSP-segregation disclosure at the commit point */}
      <window.Art10Disclosure style={{ marginBottom: 14 }} />

      {/* Art 19(2) scheme disclaimers — required on the commitment screen (BRD §8.9) */}
      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.55, marginBottom: 22 }}>{window.OPALUS_COPY.art19_2}</div>

      <div style={{ display: 'flex', gap: 12 }}>
        <Button variant="primary" onClick={onSubmit} trailingIcon={<IV.IconlyRegularLightArrowRight style={{ width: 18, height: 18 }} />}>Submit investment offer</Button>
        <Button variant="ghost" onClick={onBack}>Back</Button>
      </div>
    </Card>
  );
}

/* ============================================================ INV-19 · REFLECTION PERIOD ============================================================ */
function useTick(active) {
  const [, force] = useState(0);
  useEffect(() => { if (!active) return; const id = setInterval(() => force((n) => n + 1), 1000); return () => clearInterval(id); }, [active]);
  return Date.now();
}
function countdown(ms) {
  const d = Math.max(0, Math.floor(ms / 86400000)), h = Math.max(0, Math.floor((ms % 86400000) / 3600000)), m = Math.max(0, Math.floor((ms % 3600000) / 60000));
  return `${d}d ${String(h).padStart(2, '0')}h ${String(m).padStart(2, '0')}m`;
}

function ReflectionScreen() {
  const { state, update, go } = window.useOpalus();
  const { Button, Card } = IV;
  const now = useTick(true);
  const h = state.holdings.find((x) => x.id === state.route.params.hid) || state.holdings.find((x) => x.status === 'offer');
  const [confirmWd, setConfirmWd] = useState(false);
  const [windowExpired, setWindowExpired] = useState(false);
  if (!h) { go('dashboard'); return null; }
  const p = window.OPALUS_PROJECTS.find((x) => x.id === h.projectId);
  const remain = h.coolingEnds - now;
  const ended = remain <= 0;

  const withdraw = () => {
    if (ended) { setWindowExpired(true); return; }
    update((s) => {
      s.holdings = s.holdings.filter((x) => x.id !== h.id);
      s.wallet.balance += h.invested;
      s.wallet.transactions.unshift({ id: 'wd' + Date.now(), type: 'Investment refunded', label: `Investment refunded · ${p.title}`, amount: h.invested, date: 'Today', kind: 'in', status: 'Completed' });
    });
    go('withdrawn', { amount: h.invested });
  };
  const confirmNow = () => {
    update((s) => {
      const hh = s.holdings.find((x) => x.id === h.id);
      if (hh) hh.status = 'awaiting-signature';
      s.wallet.transactions.unshift({ id: 'rel' + Date.now(), type: 'Investment released', label: `Investment released · ${p.title}`, amount: 0, date: 'Today', kind: 'out', status: 'Completed' });
    });
    go('confirmed', { hid: h.id });
  };

  return (
    <div className="opx-container opx-fade" style={{ maxWidth: 760 }}>
      <button type="button" onClick={() => go('dashboard')} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-body)', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', marginBottom: 20, padding: 0 }}>
        <IV.IconlyRegularOutlineArrowLeft style={{ width: 18, height: 18 }} /> Dashboard
      </button>

      <Card padding="lg" radius="xl" shadow="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ background: 'var(--navy-950)', color: '#fff', padding: '28px 32px', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(100% 130% at 100% 0%, rgba(167,107,52,0.32), transparent 55%)' }} />
          <div style={{ position: 'relative' }}>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-micro)', fontWeight: 600, letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase', color: 'var(--bronze-400)' }}>Offer submitted — reflection period</div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'rgba(255,255,255,0.72)', margin: '8px 0 16px' }}>{ended ? 'Your reflection period has ended.' : `Until ${fmtDateTime(h.coolingEnds)}`}</div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>Time remaining</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 40, letterSpacing: 'var(--ls-tight)', color: ended ? 'var(--success-500)' : '#fff', fontVariantNumeric: 'tabular-nums' }}>{ended ? 'Complete' : countdown(remain)}</div>
          </div>
        </div>

        <div style={{ padding: '24px 32px' }}>
          <div style={{ border: '1px solid var(--border-faint)', borderRadius: 'var(--radius-lg)', overflow: 'hidden', marginBottom: 22 }}>
            {[['Project', p.title], ['Amount', `${window.eurC(h.invested)} (reserved in your wallet)`], ['KIIS acknowledged', `version ${h.kiisVersion}`]].map(([k, v], i) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '13px 18px', background: i % 2 ? 'var(--surface-inset)' : '#fff', fontFamily: 'var(--font-body)', fontSize: 13 }}>
                <span style={{ color: 'var(--text-body)' }}>{k}</span>
                <span style={{ fontWeight: 600, color: 'var(--ink)', textAlign: 'right', display: 'inline-flex', gap: 10, alignItems: 'center' }}>{v}{k === 'KIIS acknowledged' && <span className="opx-link" style={{ fontSize: 12 }}>Download</span>}</span>
              </div>
            ))}
          </div>

          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 22 }}>
            <span style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--cream-100)', color: 'var(--bronze-600)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}><IV.IconlyRegularLightActivity style={{ width: 16, height: 16 }} /></span>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.6, color: 'var(--text-body)' }}>When the reflection period ends, your investment is confirmed automatically, your funds are released to the project, and your contract is issued for electronic signature.</div>
          </div>

          {!confirmWd ? (
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <Button variant="primary" onClick={() => setConfirmWd(true)}>Withdraw offer</Button>
              <button type="button" onClick={confirmNow} className="opx-link" style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 12.5, marginLeft: 'auto' }}>Skip the wait & confirm now (demo) →</button>
            </div>
          ) : (
            /* INV-20 · Withdraw offer confirm dialog */
            <div style={{ border: '1.5px solid var(--bronze-300)', background: 'var(--cream-100)', borderRadius: 'var(--radius-lg)', padding: 22 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17, color: 'var(--ink)', marginBottom: 8 }}>Withdraw your {window.eur(h.invested)} offer in {p.title}?</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-body)', lineHeight: 1.6, marginBottom: 18 }}>Your funds return to your available balance immediately. No reason or fee is required.</div>
              {windowExpired && <div style={{ marginBottom: 16 }}><window.Note tone="danger" title="The reflection period has ended" icon={<span style={{ fontWeight: 700 }}>!</span>}>Your investment was confirmed. <span className="opx-link" onClick={confirmNow}>View investment</span></window.Note></div>}
              <div style={{ display: 'flex', gap: 12 }}>
                <Button variant="primary" onClick={withdraw}>Withdraw offer</Button>
                <Button variant="ghost" onClick={() => { setConfirmWd(false); setWindowExpired(false); }}>Keep my offer</Button>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
}

/* ---------- INV-20 · Withdrawn confirmation ---------- */
function WithdrawnScreen() {
  const { state, go } = window.useOpalus();
  const { Button, Card } = IV;
  const amount = state.route.params.amount || 0;
  return (
    <div className="opx-container opx-fade" style={{ maxWidth: 620 }}>
      <Card padding="lg" radius="xl" shadow="card" style={{ padding: 44, textAlign: 'center' }}>
        <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--cream-100)', color: 'var(--bronze-600)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, margin: '0 auto 18px' }}>↺</div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 26, color: 'var(--ink)', margin: '0 0 8px' }}>Offer withdrawn</h2>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', color: 'var(--text-body)', margin: '0 auto 24px', maxWidth: 420, lineHeight: 1.6 }}>{window.eur(amount)} is back in your available balance.</p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
          <Button variant="primary" onClick={() => go('dashboard')}>Go to dashboard</Button>
          <Button variant="outline" onClick={() => go('browse')}>Browse projects</Button>
        </div>
      </Card>
    </div>
  );
}

/* ============================================================ INV-21 · CONFIRMED & SIGNATURE ============================================================ */
function ConfirmedScreen() {
  const { state, update, go } = window.useOpalus();
  const { Button, Card } = IV;
  const h = state.holdings.find((x) => x.id === state.route.params.hid) || state.holdings.find((x) => x.status === 'awaiting-signature');
  const [sig, setSig] = useState('');
  const [signed, setSigned] = useState(false);
  const [executed, setExecuted] = useState(false);
  if (!h) { go('dashboard'); return null; }
  const p = window.OPALUS_PROJECTS.find((x) => x.id === h.projectId);

  const sign = () => {
    update((s) => { const hh = s.holdings.find((x) => x.id === h.id); if (hh) hh.status = 'active'; });
    setSigned(true);
  };

  return (
    <div className="opx-container opx-fade" style={{ maxWidth: 680 }}>
      <Card padding="lg" radius="xl" shadow="card" style={{ padding: 40 }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--success-50)', color: 'var(--success-600)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 30, margin: '0 auto 16px' }}>✓</div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 26, color: 'var(--ink)', margin: '0 0 8px' }}>{executed ? 'Fully executed' : signed ? 'Contract signed' : 'Investment confirmed'}</h2>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-sm)', color: 'var(--text-body)', margin: '0 auto', maxWidth: 460, lineHeight: 1.6 }}>
            {executed
              ? <>Your contract and signing certificate are in your document library.</>
              : signed
              ? <>We'll notify you when it's countersigned, then store the executed copy in your document library.</>
              : <>Your {window.eur(h.invested)} investment in {p.title} is confirmed. One step remains: sign your investment contract.</>}
          </p>
        </div>

        {!signed ? (
          <>
            <div style={{ border: '1px solid var(--border-faint)', borderRadius: 'var(--radius-lg)', overflow: 'hidden', marginBottom: 22 }}>
              {[['Project', p.title], ['Instrument', p.instrument], ['Amount', window.eurC(h.invested)], ['Investor', state.investor.name]].map(([k, v], i) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '13px 18px', background: i % 2 ? 'var(--surface-inset)' : '#fff', fontFamily: 'var(--font-body)', fontSize: 13 }}>
                  <span style={{ color: 'var(--text-body)' }}>{k}</span><span style={{ fontWeight: 600, color: 'var(--ink)', textAlign: 'right' }}>{v}</span>
                </div>
              ))}
            </div>
            <window.Field label="Type your full name to sign electronically">
              <input className="opx-amount" style={{ fontSize: 22, fontFamily: 'var(--font-display)' }} type="text" placeholder={state.investor.name} value={sig} onChange={(e) => setSig(e.target.value)} />
            </window.Field>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--text-muted)', margin: '10px 0 20px', lineHeight: 1.5 }}>Electronic signature provided in line with eIDAS. By signing you agree to the subscription agreement.</div>
            <Button variant="primary" disabled={sig.trim().length < 3} onClick={sign} leadingIcon={<IV.IconlyRegularLightEditSquare style={{ width: 18, height: 18 }} />}>Review and sign</Button>
          </>
        ) : (
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
            {!executed && <Button variant="outline" onClick={() => setExecuted(true)}>Simulate countersignature (demo)</Button>}
            <Button variant="primary" onClick={() => go('dashboard')}>Go to portfolio</Button>
            <Button variant="outline" onClick={() => go('documents')}>View documents</Button>
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { InvestScreen, ReflectionScreen, WithdrawnScreen, ConfirmedScreen, FOUR_DAYS, opalusCountdown: countdown, opalusFmtDateTime: fmtDateTime });
