// ============================================================
// Generator — inline-editable rental contract
// Ficek & Partners · NajomnaZmluva.sk
// ============================================================

// Inline editable field (contentEditable) with focus-clear behavior
// Props: id, defaultValue, placeholder, lg, xl, num, onValueChange
// Inline editable field — placeholder rendered via CSS ::before on empty contentEditable.
// The editable span is always truly empty when the user hasn't typed; CSS shows the ghost
// placeholder text (non-selectable) over it. When user types, the span fills and the
// placeholder disappears. When user deletes everything, it reappears.
const Ed = React.forwardRef(({ id, defaultValue = "", placeholder = "", lg, xl, num, select, options, block, onValueChange }, ref) => {
  const [empty, setEmpty] = React.useState(true);
  const ph = placeholder || defaultValue;
  const spanRef = React.useRef(null);

  if (select) {
    const selCls = "ed-select" + (block ? " ed-select-block" : "");
    const initial = defaultValue || (options && options[0] && options[0].v) || "";
    const [val, setVal] = React.useState(initial);
    const selectedLabel = (options.find(o => o.v === val) || options[0] || {}).label || '';
    return (
      <>
        <select
          className={selCls}
          defaultValue={initial}
          onChange={(e) => { setVal(e.target.value); onValueChange && onValueChange(e.target.value); }}
          aria-label={ph}
        >
          {options.map(o => <option key={o.v} value={o.v}>{o.label}</option>)}
        </select>
        <span className="ed-select-print" aria-hidden="true">{selectedLabel}</span>
      </>
    );
  }

  const handleInput = (e) => {
    const v = e.currentTarget.textContent;
    setEmpty(v.length === 0);
    onValueChange && onValueChange(v);
  };

  const cls = [
    "ed",
    lg && "ed-lg",
    xl && "ed-xl",
    num && "ed-num",
    empty && "ed-empty",
  ].filter(Boolean).join(" ");

  return (
    <span
      ref={spanRef}
      className={cls}
      contentEditable
      suppressContentEditableWarning
      onInput={handleInput}
      data-placeholder={ph}
      role="textbox"
      aria-label={ph}
    />
  );
});

window.Ed = Ed;


// ---------- Top Header ----------
const DOCTYPES = [
  { id: 'byt',     label: 'Byt',             icon: 'B', title: 'NÁJOMNÁ ZMLUVA O NÁJME BYTU',              ref: 'zákon č. 98/2014 Z. z. o krátkodobom nájme bytu' },
  { id: 'dom',     label: 'Stavba / Garáž',  icon: 'S', title: 'ZMLUVA O NÁJME STAVBY / GARÁŽE',            ref: '§ 663 a nasl. Občianskeho zákonníka' },
  { id: 'nebyt',   label: 'Nebytový priestor', icon: 'N', title: 'ZMLUVA O NÁJME NEBYTOVÉHO PRIESTORU',    ref: 'zákon č. 116/1990 Zb. o nájme a podnájme nebytových priestorov' },
  { id: 'pozemok', label: 'Pozemok',         icon: 'P', title: 'ZMLUVA O NÁJME POZEMKU',                    ref: '§ 663 a nasl. Občianskeho zákonníka' },
];

// Vymazať všetky vyplnené .ed polia + resetovať select-y na prvú option + vyčistiť localStorage.
// Nad DOM-om — trigger `input`/`change` event aby React Ed komponenty zaznamenali zmenu.
const clearAllFields = () => {
  if (!window.confirm('Naozaj chcete vymazať všetky údaje? Táto akcia sa nedá vrátiť späť.')) return;
  const paper = document.querySelector('article.paper');
  if (!paper) return;
  paper.querySelectorAll('.ed[contenteditable]').forEach(el => {
    el.textContent = '';
    el.dispatchEvent(new Event('input', { bubbles: true }));
  });
  paper.querySelectorAll('select.ed-select').forEach(sel => {
    sel.selectedIndex = 0;
    sel.dispatchEvent(new Event('change', { bubbles: true }));
  });
  try { localStorage.removeItem('zmluvaonajme.ed.v1'); } catch (e) {}
};
// Exponujeme globálne aby ho mohol volať aj `.paper-actions` button v Paper.jsx.
window.__clearFormFields = clearAllFields;

const GenHeader = ({ doctype, setDoctype, progress }) => (
  <header className="gen-header">
    <div className="gen-header-row">
      <a href={window.SITE_URL} className="brand">
        <div className="brand-mark">F</div>
        <div>
          <div className="brand-name">Ficek &amp; Partners</div>
          <div className="brand-sub">Advokátska kancelária</div>
        </div>
      </a>

      <div className="tabs" role="tablist" aria-label="Druh nájomnej zmluvy">
        {DOCTYPES.map(t => (
          <button
            key={t.id}
            role="tab"
            aria-selected={doctype === t.id}
            className={doctype === t.id ? 'active' : ''}
            onClick={() => setDoctype(t.id)}
          >
            <span className="tab-icon">§</span> {t.label}
          </button>
        ))}
      </div>

      <div className="header-actions">
        <div className="progress-chip" title={`${progress}% vyplnené`}>
          <div className="progress-ring" style={{ '--p': progress }}></div>
          <span>{progress} % DOKONČENÉ</span>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => window.print()}>↓ PDF</button>
        <button className="btn btn-ghost btn-sm" onClick={clearAllFields} title="Vymazať všetky vyplnené údaje">✕ Vymazať údaje</button>
        <a href={window.LEGAL_REVIEW_URL} target="_blank" rel="noopener noreferrer" className="btn btn-oxblood btn-sm">Právna kontrola</a>
      </div>
    </div>
  </header>
);

window.GenHeader = GenHeader;
window.DOCTYPES = DOCTYPES;
