// ============================================================
// Generator — inline-editable smlouva o půjčce
// JUDr. Milan Ficek, advokát · smlouva-opujcce.cz
// ============================================================

// 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 ----------
// 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('Opravdu chcete vymazat všechny údaje? Tato akce nelze vrátit zpět.')) 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('zapujcka.ed.v1'); } catch (e) {}
};
// Exponujeme globálne aby ho mohol volať aj `.paper-actions` button v Paper.jsx.
window.__clearFormFields = clearAllFields;

const GenHeader = ({ 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">JUDr. Milan Ficek</div>
          <div className="brand-sub">Advokátní kancelář</div>
        </div>
      </a>

      <div className="contract-title" aria-label="Typ smlouvy" style={{
        flex: '1 1 auto', display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 2,
        textAlign: 'center', padding: '0 16px', minWidth: 0
      }}>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 14, fontWeight: 600, letterSpacing: '0.02em', color: 'var(--ink)' }}>
          Smlouva o půjčce (zápůjčka)
        </span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3, #5a5a5a)' }}>
          § 2390 zákona č. 89/2012 Sb., občanský zákoník
        </span>
      </div>

      <div className="header-actions">
        <div className="progress-chip" title={`${progress} % vyplněno`}>
          <div className="progress-ring" style={{ '--p': progress }}></div>
          <span>{progress} % DOKONČENO</span>
        </div>
        <button className="btn btn-ghost btn-sm btn-action" onClick={() => window.print()} title="Stáhnout PDF" aria-label="Stáhnout PDF">
          <span className="btn-icon" aria-hidden="true">↓</span><span className="btn-label">PDF</span>
        </button>
        <button className="btn btn-ghost btn-sm btn-action" onClick={clearAllFields} title="Vymazat všechny vyplněné údaje" aria-label="Vymazat všechny vyplněné údaje">
          <span className="btn-icon" aria-hidden="true">✕</span><span className="btn-label">Vymazat údaje</span>
        </button>
        <a href={window.LEGAL_REVIEW_URL} target="_blank" rel="noopener noreferrer" className="btn btn-oxblood btn-sm btn-action btn-cta" title="Právní kontrola advokátem" aria-label="Právní kontrola advokátem">
          <span className="btn-label">Právní kontrola</span>
          <span className="btn-label-short" aria-hidden="true">Kontrola</span>
        </a>
      </div>
    </div>
  </header>
);

window.GenHeader = GenHeader;
