// ============================================================
// Reusable atoms + icons
// ============================================================

const Ico = {
  Check: () => (<svg className="ico" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>),
  Plus: () => (<svg className="ico" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>),
  X: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>),
  Trash: () => (<svg className="ico" viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>),
  Chevron: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"/></svg>),
  ChevronRight: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><polyline points="9 18 15 12 9 6"/></svg>),
  Bold: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M7 4h6a4 4 0 0 1 4 4 4 4 0 0 1-2 3.5A4.5 4.5 0 0 1 18 16a4 4 0 0 1-4 4H7z"/></svg>),
  Italic: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>),
  Underline: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M6 4v7a6 6 0 0 0 12 0V4"/><line x1="4" y1="21" x2="20" y2="21"/></svg>),
  Link: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7 0l4-4a5 5 0 1 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-4 4a5 5 0 0 0 7 7l1-1"/></svg>),
  List: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4.5" cy="6" r="1"/><circle cx="4.5" cy="12" r="1"/><circle cx="4.5" cy="18" r="1"/></svg>),
  Grip: () => (<svg className="ico ico-xs" viewBox="0 0 24 24" fill="currentColor" stroke="none"><circle cx="9" cy="6" r="1.5"/><circle cx="15" cy="6" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="18" r="1.5"/></svg>),
  Eye: () => (<svg className="ico" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>),
  Send: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>),
  Save: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>),
  File: () => (<svg className="ico ico-lg" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>),
  Template: () => (<svg className="ico ico-lg" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="21" x2="9" y2="9"/></svg>),
  ArrowUp: () => (<svg className="ico ico-xs" viewBox="0 0 24 24"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>),
  ArrowDown: () => (<svg className="ico ico-xs" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>),
  Sun: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><line x1="12" y1="2" x2="12" y2="4"/><line x1="12" y1="20" x2="12" y2="22"/><line x1="4.93" y1="4.93" x2="6.34" y2="6.34"/><line x1="17.66" y1="17.66" x2="19.07" y2="19.07"/><line x1="2" y1="12" x2="4" y2="12"/><line x1="20" y1="12" x2="22" y2="12"/><line x1="4.93" y1="19.07" x2="6.34" y2="17.66"/><line x1="17.66" y1="6.34" x2="19.07" y2="4.93"/></svg>),
  Bowl: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M3 11h18a9 9 0 0 1-18 0z"/><line x1="6" y1="3" x2="6" y2="6"/><line x1="10" y1="3" x2="10" y2="6"/><line x1="14" y1="3" x2="14" y2="6"/></svg>),
  Moon: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>),
  Sparkles: () => (<svg className="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M9 3L10.2 7.8 15 9L10.2 10.2 9 15 7.8 10.2 3 9 7.8 7.8z"/><path d="M18 4L18.6 5.8 20.4 6.5 18.6 7.2 18 9 17.4 7.2 15.6 6.5 17.4 5.8z"/><path d="M18 15L18.5 16.4 20 17 18.5 17.6 18 19 17.4 17.6 16 17 17.4 16.4z"/></svg>),
  CheckCircle: () => (<svg className="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>),
  Lock: () => (<svg className="ico ico-sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>),
  Sparkle: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>),
  Pencil: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>),
  Settings: () => (<svg className="ico" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>),
  User: () => (<svg className="ico" viewBox="0 0 24 24"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>),
  Video: () => (<svg className="ico" viewBox="0 0 24 24"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>),
  Chat: () => (<svg className="ico" viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>),
  Logout: () => (<svg className="ico" viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>),
  Download: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>),
  Sliders: () => (<svg className="ico" viewBox="0 0 24 24"><line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/></svg>),
  Leaf: () => (
    <svg viewBox="0 0 32 32" fill="none">
      <path d="M16 4 C 8 6 5 14 8 22 C 11 18 14 16 16 14 C 14 18 12 22 10 25 C 16 27 24 24 26 16 C 22 16 19 17 16 18 C 19 14 22 11 26 9 C 22 5 19 4 16 4 Z" fill="#3F7159"/>
      <path d="M16 4 C 18 8 19 12 20 18" stroke="#1E3A2B" strokeWidth="0.8" strokeLinecap="round"/>
    </svg>
  ),
  Calendar: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>),
  Pill: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M10.5 20.5 20.5 10.5a5 5 0 0 0-7-7L3.5 13.5a5 5 0 0 0 7 7z"/><line x1="8.5" y1="8.5" x2="15.5" y2="15.5"/></svg>),
  Lab: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M9 3v8l-5 8a2 2 0 0 0 2 3h12a2 2 0 0 0 2-3l-5-8V3"/><line x1="7" y1="3" x2="17" y2="3"/></svg>),
  Search: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.5" y2="16.5"/></svg>),
  More: () => (<svg className="ico ico-sm" viewBox="0 0 24 24" fill="currentColor" stroke="none"><circle cx="6" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="18" cy="12" r="1.5"/></svg>),
  Heart: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z"/></svg>),
  Activity: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>),
  Sleep: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>),
  Upload: () => (<svg className="ico" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>),
  Refresh: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>),
  Warn: () => (<svg className="ico ico-sm" viewBox="0 0 24 24"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>),
  Spinner: () => (<svg className="ico spin" viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-6.219-8.56" /></svg>),
  FileText: () => (<svg className="ico" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/></svg>),
};

// Avatar
function Avatar({ name, color, size = 28 }) {
  const initials = name.split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: color || 'linear-gradient(135deg, #C7BFAE, #8B9B85)',
      color: 'white', display: 'grid', placeItems: 'center',
      fontWeight: 500, fontSize: size * 0.40, flexShrink: 0,
    }}>{initials}</div>
  );
}

// Rich-text box. Manages its own contentEditable DOM via a ref so re-renders
// from parent state updates never reset the caret (which caused "typing
// backwards"). External value changes only sync when the field is NOT focused.
function RichText({ value, onChange, placeholder = 'Recomendação' }) {
  const ref = React.useRef(null);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (document.activeElement !== el && el.innerHTML !== (value || '')) {
      el.innerHTML = value || '';
    }
  });

  const exec = (cmd, arg) => {
    const el = ref.current;
    if (el) el.focus();
    document.execCommand(cmd, false, arg);
    if (el) onChange?.(el.innerHTML);
  };

  return (
    <div>
      <div className="rt-toolbar">
        <button type="button" title="Bullets" onMouseDown={e => { e.preventDefault(); exec('insertUnorderedList'); }}><Ico.List/></button>
        <button type="button" title="Bold" onMouseDown={e => { e.preventDefault(); exec('bold'); }}><Ico.Bold/></button>
        <button type="button" title="Italic" onMouseDown={e => { e.preventDefault(); exec('italic'); }}><Ico.Italic/></button>
        <button type="button" title="Underline" onMouseDown={e => { e.preventDefault(); exec('underline'); }}><Ico.Underline/></button>
        <button type="button" title="Link" onMouseDown={e => { e.preventDefault(); const u = window.prompt('URL do link'); if (u) exec('createLink', u); }}><Ico.Link/></button>
      </div>
      <div
        ref={ref}
        className="rt-area"
        contentEditable
        suppressContentEditableWarning
        onInput={e => onChange?.(e.currentTarget.innerHTML)}
        data-placeholder={placeholder}
      />
    </div>
  );
}

// Add-section affordance
function AddSection({ label = 'Adicionar seção', onClick }) {
  return (
    <div className="add-section" onClick={onClick}>
      <Ico.Plus /> {label}
    </div>
  );
}

// ============================================================
// Patient + Doctor + Review — context wrappers.
// PatientProvider + usePatient are now supplied by plan-store.jsx;
// this file only keeps the no-op stubs that other components still
// import (legacy AI banners / hints — all return null now).
// ============================================================

// ReviewContext stub — kept for compatibility with old imports.
const ReviewContext = React.createContext(null);
function ReviewProvider({ children }) {
  const value = React.useMemo(() => ({
    reviewedMap: {}, setReviewed: () => {},
    total: 0, reviewedCount: 0, allReviewed: false,
  }), []);
  return <ReviewContext.Provider value={value}>{children}</ReviewContext.Provider>;
}
function useReview() { return React.useContext(ReviewContext) || { reviewedMap: {}, setReviewed: () => {} }; }

// AI-flavored components are no-op stubs (legacy).
function ChapterReviewBanner() { return null; }
function WelcomeToast() { return null; }
function AIRationale() { return null; }
function AIHint() { return null; }

// Section header (Capítulo + responsável). The Save button uses chapterId
// to mark the chapter as saved in PlanContext and fires a global toast.
function SectionHeader({ title, sub, responsavel, chapterId }) {
  const { doctor } = usePatient();
  const { plan, saveChapter } = usePlan();
  const who = responsavel || doctor.name;
  const saved = chapterId && plan.savedChapters && plan.savedChapters[chapterId];

  // Traduz título/subtítulo pelo idioma do plano (quando há tradução do capítulo).
  const lang = (plan && plan.lang) || 'pt-BR';
  let dispTitle = title, dispSub = sub;
  if (chapterId && typeof tr === 'function') {
    const tk = 'step.' + chapterId, sk = 'sub.' + chapterId;
    const tt = tr(tk, lang); if (tt && tt !== tk) dispTitle = tt;
    const ss = tr(sk, lang); if (ss && ss !== sk) dispSub = ss;
  }

  const handleSave = () => {
    if (chapterId) saveChapter(chapterId);
    blifeToast('Capítulo salvo localmente no navegador');
  };

  return (
    <div className="section-header">
      <div>
        <div className="crumb">{typeof fl === 'function' ? fl('Capítulo') : 'Capítulo'}</div>
        <h1>{dispTitle}</h1>
        {dispSub && <div className="sub">{dispSub}</div>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {who && (
          <div className="responsavel">
            <div className="av">{who.split(' ').map(s=>s[0]).slice(0,2).join('')}</div>
            <div>
              <div className="lbl">Responsável</div>
              <div style={{ fontWeight: 500 }}>{who}</div>
            </div>
          </div>
        )}
        <button
          className={'btn' + (saved ? ' saved' : '')}
          onClick={handleSave}
          title={saved ? 'Marcado como salvo · clique para reconfirmar' : 'Marcar este capítulo como salvo'}
        >
          {saved ? <><Ico.Check/> {typeof fl === 'function' ? fl('Salvo') : 'Salvo'}</> : <><Ico.Save/> {typeof fl === 'function' ? fl('Salvar capítulo') : 'Salvar capítulo'}</>}
        </button>
      </div>
    </div>
  );
}

// Card wrapper used by section editors
function SectionCard({ title, count, onDelete, children, right }) {
  return (
    <div className="card">
      <div className="card-head">
        <span className="grip"><Ico.Grip/></span>
        <span className="title">{title}</span>
        {count != null && <span className="pill">{count}</span>}
        <div className="right">
          {right}
          {onDelete && <button className="btn danger sm" onClick={onDelete}><Ico.Trash/></button>}
        </div>
      </div>
      <div className="card-body">{children}</div>
    </div>
  );
}

// Status pill (re-export for editors)
function StatusPill({ kind = 'ok', children }) {
  return (
    <span className={'status ' + kind}>
      <span className="d"/> {children}
    </span>
  );
}

Object.assign(window, { Ico, Avatar, RichText, AddSection, SectionHeader, SectionCard, StatusPill, ReviewProvider, useReview, ChapterReviewBanner, WelcomeToast, AIRationale, AIHint });
