// screens-edit.jsx — Kompozytor (real app: 3-col, Luthor RTE) + AI variant.
// Rebuilt to match HomeBudget/szacownia: AppShell > sub-topbar > [Struktura | Edytor | Blokoteka/Zmienne/Dane].
// Exports a shared <KompozytorFrame> so the RCiWN section screen can reuse it.

// ── Operat structure (matches real section types + emoji icons) ────────────────
const KOMP_SECTIONS = [
  { t: 'Strona tytułowa',            type: 'title' },
  { t: 'Spis treści',                type: 'toc' },
  { t: 'Cel i przedmiot wyceny',     type: 'text' },
  { t: 'Opis stanu prawnego',        type: 'text' },
  { t: 'Opis działki i otoczenia',   type: 'text' },
  { t: 'Tabela RCN',                 type: 'rciwn' },
  { t: 'Załącznik mapowy',           type: 'map' },
  { t: 'Analiza i wartość rynkowa',  type: 'text' },
  { t: 'Klauzule i założenia',       type: 'kw' },
];

const SECTION_EMOJI = { title: '📄', toc: '📋', text: '§', rciwn: '📊', map: '🗺', mpzp: '📐', kw: '📖', wyciag: '📑', photos: '📷' };
const SECTION_TYPE_LABEL = { title: 'Strona tytułowa', toc: 'Spis treści', text: 'Sekcja tekstowa', rciwn: 'Tabela RCN', map: 'Mapa', mpzp: 'Plan miejscowy (MPZP)', kw: 'Księga Wieczysta', wyciag: 'Wyciąg z operatu', photos: 'Zdjęcia nieruchomości' };

const ADD_OPTIONS = ['Sekcja tekstowa', 'Tabela RCN', 'Mapa', 'Zdjęcia nieruchomości', 'Plan miejscowy (MPZP)', 'Księga Wieczysta', 'Wyciąg z operatu', 'Spis treści'];

// ── Sub-topbar (kompozytor page header, 48px) ─────────────────────────────────
const KompSubTopbar = () => (
  <div style={{ height: 48, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 16px', borderBottom: `1px solid ${T.border}`, background: T.surface, gap: 12 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
      <span style={{ display: 'inline-flex', transform: 'rotate(180deg)', color: T.ink3, padding: '4px 6px' }}><Icon name="chevR" size={14} color={T.ink3} /></span>
      <div style={{ width: 1, height: 16, background: T.border }} />
      <span style={{ fontSize: 13.5, fontWeight: 500, color: T.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 380 }}>
        Operat 2026‑0142 <span style={{ color: T.ink3, fontWeight: 400 }}>· Klonowa 14, Stara Wieś</span>
      </span>
      <span style={{ fontFamily: T.mono, fontSize: 10.5, color: T.ink4, flexShrink: 0 }}>Szkic</span>
    </div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <button style={{ height: 30, padding: '0 14px', border: `1px solid ${T.border}`, borderRadius: 3, fontSize: 12.5, fontWeight: 500, color: T.ink4, background: 'transparent', cursor: 'default', opacity: 0.55 }}>Zapisz</button>
      <button style={{ height: 30, padding: '0 14px', border: `1px solid ${T.border}`, borderRadius: 3, fontSize: 12.5, color: T.ink2, background: 'transparent', cursor: 'pointer' }}>Podgląd</button>
      <button style={{ height: 30, padding: '0 14px', background: T.ink, color: T.surface, border: 'none', borderRadius: 3, fontSize: 12.5, fontWeight: 500, cursor: 'pointer' }}>Eksportuj</button>
    </div>
  </div>
);

// ── Left column — Struktura (SectionsList) ────────────────────────────────────
const SectionsListReal = ({ activeKey }) => (
  <div style={{ borderRight: `1px solid ${T.border}`, background: T.surface, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '12px 12px', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <span style={{ fontFamily: T.mono, fontSize: 10, color: T.ink3, letterSpacing: '0.12em', textTransform: 'uppercase' }}>Struktura</span>
      <Icon name="gear" size={14} color={T.ink3} />
    </div>
    <div style={{ flex: 1, overflow: 'auto', padding: '8px 8px' }}>
      {KOMP_SECTIONS.map((s, i) => {
        const active = s.t === activeKey;
        return (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 8px', borderRadius: 4, background: active ? T.surface2 : 'transparent', color: active ? T.ink : T.ink2, cursor: 'pointer' }}>
            <span style={{ color: T.ink4, fontSize: 13, lineHeight: 1, opacity: active ? 0.9 : 0.45 }}>⠿</span>
            <span style={{ fontSize: 11, width: 16, textAlign: 'center', flexShrink: 0 }}>{SECTION_EMOJI[s.type]}</span>
            <span style={{ flex: 1, fontSize: 12.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', lineHeight: 1.3, fontWeight: active ? 500 : 400 }}>{s.t}</span>
          </div>
        );
      })}
    </div>
    <div style={{ borderTop: `1px solid ${T.border}`, padding: '8px 8px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 8px', marginBottom: 6 }}>
        <span style={{ fontFamily: T.mono, fontSize: 10, color: T.ink4, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Dodaj sekcję</span>
        <Icon name="chevD" size={12} color={T.ink4} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {ADD_OPTIONS.map((label, i) => (
          <button key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', borderRadius: 4, fontSize: 12, color: T.ink3, background: 'transparent', border: 'none', textAlign: 'left', cursor: 'pointer' }}>
            <Icon name="plus" size={11} color={T.ink4} />
            {label}
          </button>
        ))}
      </div>
    </div>
  </div>
);

// ── Luthor RTE toolbar ────────────────────────────────────────────────────────
const TBtn = ({ children, active, w }) => (
  <span style={{ height: 28, minWidth: w || 28, padding: '0 6px', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', borderRadius: 3, fontSize: 12, border: '1px solid transparent', background: active ? T.ink : 'transparent', color: active ? T.surface : T.ink2, cursor: 'pointer', flexShrink: 0 }}>{children}</span>
);
const TSep = () => <div style={{ width: 1, height: 20, background: T.border, margin: '0 2px', flexShrink: 0 }} />;
const TSelect = ({ children, w }) => (
  <span style={{ height: 28, padding: '0 8px', display: 'inline-flex', alignItems: 'center', gap: 8, borderRadius: 3, fontSize: 12, border: `1px solid ${T.border}`, background: T.surface2, color: T.ink2, width: w, cursor: 'pointer', flexShrink: 0 }}>
    <span style={{ flex: 1 }}>{children}</span>
    <Icon name="chevD" size={11} color={T.ink4} />
  </span>
);

const RTEToolbar = () => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 2, padding: '5px 8px', borderBottom: `1px solid ${T.border}`, background: T.surface2, borderTopLeftRadius: 4, borderTopRightRadius: 4, overflow: 'hidden' }}>
    <TBtn>↶</TBtn>
    <TBtn>↷</TBtn>
    <TSep />
    <TBtn active><b style={{ fontSize: 13 }}>B</b></TBtn>
    <TBtn><i style={{ fontFamily: T.serif, fontSize: 13 }}>I</i></TBtn>
    <TBtn><span style={{ textDecoration: 'underline' }}>U</span></TBtn>
    <TBtn><span style={{ textDecoration: 'line-through' }}>S</span></TBtn>
    <TSep />
    <TSelect w={108}>Akapit</TSelect>
    <TSelect w={66}>12 px</TSelect>
    <TSep />
    <TBtn w={32}><span style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}><b style={{ fontSize: 12, lineHeight: 1 }}>A</b><span style={{ width: 14, height: 3, borderRadius: 1, background: T.ink }} /></span></TBtn>
    <TBtn>▦</TBtn>
    <TSep />
    <TBtn>•≡</TBtn>
    <TBtn>1.≡</TBtn>
    <TSep />
    <TBtn>🔗</TBtn>
    <TBtn>⊞</TBtn>
    <TBtn>🖼</TBtn>
  </div>
);

// ── Center — Section editor (header + RTE) ────────────────────────────────────
const SectionEditorHeader = ({ title, typeLabel, status }) => (
  <div style={{ padding: '12px 24px', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'flex-start', gap: 12, flexShrink: 0 }}>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontFamily: T.serif, fontSize: 16, fontWeight: 500, color: T.ink, letterSpacing: '-0.01em', borderBottom: '1px solid transparent', paddingBottom: 2 }}>{title}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
        <span style={{ fontFamily: T.mono, fontSize: 10, color: T.ink4, textTransform: 'uppercase', letterSpacing: '0.1em' }}>{typeLabel}</span>
        <span style={{ fontFamily: T.mono, fontSize: 10, color: T.ink4 }}>{status}</span>
      </div>
    </div>
    <span style={{ width: 32, height: 32, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', borderRadius: 5, color: T.ink3 }}><Icon name="gear" size={15} stroke={1.7} color={T.ink3} /></span>
  </div>
);

const RTEHint = () => (
  <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8 }}>
    <span style={{ fontSize: 11.5, color: T.ink4 }}>Użyj <code style={{ fontFamily: T.mono, background: T.surface2, padding: '1px 4px', borderRadius: 3 }}>{'{{zmienna}}'}</code> dla dynamicznych wartości</span>
  </div>
);

const TextSectionEditor = () => (
  <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', padding: '16px 24px' }}>
    <RTEHint />
    <div style={{ flex: 1, border: `1px solid ${T.border}`, borderRadius: 4, background: T.surface, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <RTEToolbar />
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 26px', fontFamily: T.sans, fontSize: 14, lineHeight: 1.75, color: T.ink }}>
        <p style={{ margin: '0 0 14px' }}>
          Przedmiotem wyceny jest nieruchomość gruntowa stanowiąca działkę ewidencyjną nr&nbsp;<b style={{ fontWeight: 600 }}>127/3</b>, położoną w&nbsp;obrębie 0024 Stara Wieś, gmina Brzeg Dolny, powiat wołowski, województwo dolnośląskie, o&nbsp;powierzchni <b style={{ fontWeight: 600 }}>3&nbsp;247&nbsp;m²</b>.
        </p>
        <p style={{ margin: '0 0 14px' }}>
          Otoczenie nieruchomości stanowi zabudowa mieszkaniowa jednorodzinna o&nbsp;niskiej intensywności. Dojazd drogą gminną o&nbsp;nawierzchni asfaltowej. Działka uzbrojona w&nbsp;sieć:
        </p>
        <ul style={{ margin: '0 0 14px', paddingLeft: 22 }}>
          <li style={{ marginBottom: 3 }}>elektroenergetyczną,</li>
          <li style={{ marginBottom: 3 }}>wodociągową,</li>
          <li>kanalizacji sanitarnej.</li>
        </ul>
        <p style={{ margin: 0 }}>
          Działka posiada regularny kształt zbliżony do&nbsp;prostokąta, teren płaski, bez&nbsp;widocznych obciążeń. Nieruchomość położona w&nbsp;strefie zabudowy mieszkaniowej zgodnie z&nbsp;obowiązującym MPZP <span style={{ display: 'inline-block', width: 1, height: 16, background: T.ink, verticalAlign: 'text-bottom', marginLeft: 1 }} />
        </p>
      </div>
    </div>
  </div>
);

// ── Right column — Blokoteka / Zmienne / Dane działki ─────────────────────────
const RightTabs = ({ active = 'blokoteka', children }) => (
  <div style={{ borderLeft: `1px solid ${T.border}`, background: T.surface, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
    <div style={{ display: 'flex', borderBottom: `1px solid ${T.border}`, flexShrink: 0 }}>
      {[['blokoteka', 'Blokoteka'], ['zmienne', 'Zmienne'], ['dzialka', 'Dane działki']].map(([k, label]) => (
        <button key={k} style={{ flex: 1, height: 36, fontSize: 11.5, fontWeight: 500, border: 'none', cursor: 'pointer', borderBottom: active === k ? `2px solid ${T.ink}` : '2px solid transparent', background: 'transparent', color: active === k ? T.ink : T.ink3 }}>{label}</button>
      ))}
    </div>
    <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>{children}</div>
  </div>
);

const BlokCard = ({ title, preview, chips = [], hot }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: '10px', borderRadius: 4, border: `1px solid ${hot ? T.ink : T.border}`, background: T.surface, cursor: 'grab' }}>
    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 4 }}>
      <span style={{ fontSize: 12.5, fontWeight: 500, color: T.ink, lineHeight: 1.2, flex: 1 }}>{title}</span>
      <Icon name="grip" size={11} color={T.ink4} />
    </div>
    {preview && <p style={{ margin: 0, fontSize: 11.5, color: T.ink3, lineHeight: 1.45, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{preview}</p>}
    {chips.length > 0 && (
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
        {chips.map((c, i) => <span key={i} style={{ fontFamily: T.mono, fontSize: 9.5, color: T.ink3, padding: '1px 6px', border: `1px solid ${T.border}`, borderRadius: 2 }}>{c}</span>)}
      </div>
    )}
  </div>
);

const BlokGroup = ({ name, count, open, children }) => (
  <div style={{ marginBottom: 12 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 4px', color: T.ink3 }}>
      <Icon name={open ? 'chevD' : 'chevR'} size={11} color="currentColor" />
      <span style={{ flex: 1, fontFamily: T.mono, fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{name}</span>
      <span style={{ fontFamily: T.mono, fontSize: 10, color: T.ink4 }}>{count}</span>
    </div>
    {open && <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 4 }}>{children}</div>}
  </div>
);

const BlokotekaPanel = () => (
  <>
    <div style={{ padding: '12px 12px 10px', borderBottom: `1px solid ${T.border}` }}>
      <span style={{ display: 'block', fontFamily: T.mono, fontSize: 10, color: T.ink3, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>Blokoteka</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, height: 28, padding: '0 10px', border: `1px solid ${T.border}`, borderRadius: 3, background: T.surface }}>
        <Icon name="search" size={12} color={T.ink4} />
        <span style={{ flex: 1, fontSize: 12, color: T.ink4 }}>Szukaj…</span>
        <span style={{ fontFamily: T.mono, fontSize: 10, color: T.ink4 }}>86</span>
      </div>
    </div>
    <div style={{ flex: 1, overflow: 'auto', padding: '8px 8px' }}>
      <BlokGroup name="Lokalizacja" count={14} open>
        <BlokCard hot title="Opis działki — wieś, MN" preview="Działka o regularnym kształcie, w otoczeniu zabudowy mieszkaniowej jednorodzinnej…" chips={['{{nr_dzialki}}', '{{powierzchnia}}']} />
        <BlokCard title="Dojazd — droga gminna" preview="Dojazd drogą gminną o nawierzchni asfaltowej, dostęp do sieci uzbrojenia…" chips={['{{gmina}}']} />
      </BlokGroup>
      <BlokGroup name="Metodologia" count={9} open>
        <BlokCard title="Podejście porównawcze — korekta ceny średniej" preview="Do określenia wartości rynkowej zastosowano metodę korygowania ceny średniej…" />
      </BlokGroup>
      <BlokGroup name="Klauzule formalne" count={21} />
      <BlokGroup name="Rynek lokalny" count={18} />
    </div>
    <div style={{ borderTop: `1px solid ${T.border}`, padding: '10px 12px', background: T.surface3, textAlign: 'center' }}>
      <span style={{ fontFamily: T.mono, fontSize: 10.5, color: T.ink4, letterSpacing: '0.04em' }}>Przeciągnij blok do edytora lub <span style={{ color: T.ink, textDecoration: 'underline' }}>kliknij</span></span>
    </div>
  </>
);

// ── Shared 3-column frame (reused by RCiWN section screen) ────────────────────
const KompozytorFrame = ({ activeKey, center, rightActive = 'blokoteka', right, navCollapsed = true }) => (
  <AppShell activeNav="operaty" navCollapsed={navCollapsed}>
    <div style={{ height: '100%', display: 'grid', gridTemplateRows: '48px 1fr', overflow: 'hidden' }}>
      <KompSubTopbar />
      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr 260px', overflow: 'hidden', height: '100%' }}>
        <SectionsListReal activeKey={activeKey} />
        <div style={{ background: T.bg, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>{center}</div>
        <RightTabs active={rightActive}>{right || <BlokotekaPanel />}</RightTabs>
      </div>
    </div>
  </AppShell>
);

// ── Screen: Kompozytor (text section active, RTE) ─────────────────────────────
const ScreenKompozytor = () => (
  <KompozytorFrame
    activeKey="Opis działki i otoczenia"
    center={
      <>
        <SectionEditorHeader title="Opis działki i otoczenia" typeLabel="Sekcja tekstowa" status="Zapisano 09:14" />
        <TextSectionEditor />
      </>
    }
  />
);

// ── Screen: Kompozytor + Asystent AI ──────────────────────────────────────────
const AiPanel = () => (
  <>
    <div style={{ padding: '12px 14px', borderBottom: `1px solid ${T.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 18, color: T.ink }}>✦</span>
        <div>
          <div style={{ fontSize: 13, color: T.ink, fontWeight: 500 }}>Asystent</div>
          <div style={{ fontSize: 10.5, color: T.ink3, fontFamily: T.mono, letterSpacing: '0.04em' }}>Claude Haiku · 12 / 50 dziś</div>
        </div>
      </div>
      <Icon name="x" size={14} color={T.ink3} />
    </div>
    <div style={{ padding: '12px 14px', borderBottom: `1px solid ${T.border}`, background: T.surface3 }}>
      <Caps style={{ marginBottom: 8 }}>Tryb</Caps>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 0, border: `1px solid ${T.border}`, borderRadius: 4, background: T.surface, padding: 3 }}>
        {[['Popraw', true], ['Rozwiń', false], ['Skróć', false], ['Uformal.', false], ['Czat', false]].map(([l, sel], i) => (
          <button key={i} style={{ height: 26, background: sel ? T.ink : 'transparent', color: sel ? T.surface : T.ink2, border: 'none', borderRadius: 3, fontSize: 11.5, fontWeight: sel ? 500 : 400, fontFamily: T.sans, cursor: 'pointer' }}>{l}</button>
        ))}
      </div>
    </div>
    <div style={{ flex: 1, overflow: 'auto', padding: '14px 14px' }}>
      <Caps style={{ marginBottom: 10 }}>Propozycja · diff</Caps>
      <div style={{ border: `1px solid ${T.border}`, borderRadius: 4, overflow: 'hidden', background: T.surface }}>
        <div style={{ background: 'rgba(153, 27, 27, 0.04)', padding: '10px 12px', borderBottom: `1px solid ${T.border}`, fontSize: 12.5, lineHeight: 1.55, color: T.ink3, textDecoration: 'line-through' }}>
          Działka posiada regularny kształt zbliżony do prostokąta, teren płaski, bez widocznych obciążeń.
        </div>
        <div style={{ background: 'rgba(21, 128, 61, 0.045)', padding: '10px 12px', fontSize: 12.5, lineHeight: 1.55, color: T.ink }}>
          Działka cechuje się <b style={{ background: 'rgba(21, 128, 61, 0.12)', padding: '0 2px', borderRadius: 2 }}>regularnym kształtem zbliżonym do&nbsp;prostokąta</b>, ukształtowaniem płaskim oraz <b style={{ background: 'rgba(21, 128, 61, 0.12)', padding: '0 2px', borderRadius: 2 }}>brakiem obciążeń ujawnionych w&nbsp;KW</b>.
        </div>
      </div>
      <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
        <Btn variant="ghost" size="sm">Odrzuć</Btn>
        <Btn variant="primary" size="sm" icon="check">Zastosuj</Btn>
      </div>
      <div style={{ marginTop: 14, padding: 12, background: T.surface3, borderRadius: 4, fontSize: 11.5, color: T.ink3, lineHeight: 1.5 }}>
        AI nigdy nie nadpisuje treści bez Twojej akceptacji.
      </div>
    </div>
    <div style={{ padding: 12, borderTop: `1px solid ${T.border}` }}>
      <div style={{ border: `1px solid ${T.border}`, borderRadius: 4, padding: 10, fontSize: 12.5, color: T.ink4, background: T.surface }}>
        Opisz, co poprawić…
        <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontFamily: T.mono, fontSize: 10, color: T.ink4, letterSpacing: '0.04em' }}>⌘ + ↵ wyślij</span>
          <Btn variant="primary" size="sm" icon="sparkle">Wyślij</Btn>
        </div>
      </div>
    </div>
  </>
);

const ScreenKompozytorAI = () => (
  <KompozytorFrame
    activeKey="Opis działki i otoczenia"
    rightActive="zmienne"
    right={<AiPanel />}
    center={
      <>
        <SectionEditorHeader title="Opis działki i otoczenia" typeLabel="Sekcja tekstowa" status="Niezapisane zmiany" />
        <TextSectionEditor />
      </>
    }
  />
);

Object.assign(window, {
  ScreenKompozytor, ScreenKompozytorAI,
  KompozytorFrame, SectionEditorHeader, RTEToolbar, BlokotekaPanel, RightTabs,
});
