/* ========== Translation Templates ========== */
function TemplatesView() {
  const state = useStore();
  const [selectedId, setSelectedId] = useState(state.translationTemplates[0]?.id || null);
  const [showNew, setShowNew] = useState(false);
  const [showToast, toastEl] = useToast();

  const tpl = state.translationTemplates.find(t => t.id === selectedId);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 16, alignItems: 'start' }}>
        <div className="card">
          <div className="card-header">
            <h3>Templates</h3>
            <div className="spacer"/>
            <button className="btn ghost icon" onClick={() => setShowNew(true)} title="New template">
              <Icon name="plus" size={14}/>
            </button>
          </div>
          <div style={{ maxHeight: 540, overflow: 'auto' }}>
            {state.translationTemplates.map(t => (
              <div
                key={t.id}
                onClick={() => setSelectedId(t.id)}
                style={{
                  padding: '11px 14px',
                  borderBottom: '1px solid var(--ink-100)',
                  cursor: 'pointer',
                  background: t.id === selectedId ? 'var(--navy-50)' : 'transparent',
                  borderLeft: t.id === selectedId ? '3px solid var(--navy-700)' : '3px solid transparent',
                }}
              >
                <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink-900)' }}>{t.title}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 2 }}>
                  {t.sourceLang} → {t.targetLang}
                </div>
              </div>
            ))}
            {state.translationTemplates.length === 0 && (
              <div className="empty"><p>No templates yet</p></div>
            )}
          </div>
        </div>

        <div>
          {tpl ? (
            <TemplateEditor
              key={tpl.id}
              template={tpl}
              onCopy={(label) => showToast(`${label} copied to clipboard`)}
              onDelete={() => {
                if (confirm('Delete this template?')) {
                  window.PVStore.deleteTranslationTemplate(tpl.id);
                  setSelectedId(state.translationTemplates.filter(t=>t.id!==tpl.id)[0]?.id || null);
                }
              }}
            />
          ) : (
            <div className="card"><div className="empty"><h4>No template selected</h4><p>Create a new template to get started.</p><button className="btn primary" onClick={() => setShowNew(true)}><Icon name="plus" size={14}/> New template</button></div></div>
          )}
        </div>
      </div>

      {showNew && (
        <TemplateModal
          onClose={() => setShowNew(false)}
          onSaved={(id) => { setShowNew(false); setSelectedId(id); }}
        />
      )}
      {toastEl}
    </div>
  );
}

function TemplateEditor({ template, onCopy, onDelete }) {
  const [showEdit, setShowEdit] = useState(false);

  const copy = async (text, label) => {
    try {
      await navigator.clipboard.writeText(text);
      onCopy(label);
    } catch (e) {
      alert('Copy failed');
    }
  };

  return (
    <div className="card">
      <div className="card-header">
        <div>
          <h3>{template.title}</h3>
          <div className="subtle" style={{ fontSize: 12, marginTop: 2 }}>{template.sourceLang} → {template.targetLang}</div>
        </div>
        <div className="spacer"/>
        <button className="btn sm" onClick={() => setShowEdit(true)}><Icon name="edit" size={12}/> Edit</button>
        <button className="btn danger sm" onClick={onDelete}><Icon name="trash" size={12}/></button>
      </div>
      <div className="card-body">
        <div className="form-row two">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
              <label style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Source ({template.sourceLang})</label>
              <button className="btn ghost sm" onClick={() => copy(template.source, 'Source')}>
                <Icon name="copy" size={12}/> Copy
              </button>
            </div>
            <pre style={{
              background: 'var(--ink-50)',
              border: '1px solid var(--ink-200)',
              borderRadius: 8,
              padding: '14px 16px',
              fontSize: 13,
              fontFamily: 'var(--font-lao)',
              whiteSpace: 'pre-wrap',
              minHeight: 280,
              margin: 0,
              lineHeight: 1.7,
            }}>{template.source}</pre>
          </div>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
              <label style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Translation ({template.targetLang})</label>
              <button className="btn ghost sm" onClick={() => copy(template.target, 'Translation')}>
                <Icon name="copy" size={12}/> Copy
              </button>
            </div>
            <pre style={{
              background: '#fff',
              border: '1px solid var(--navy-100)',
              borderRadius: 8,
              padding: '14px 16px',
              fontSize: 13,
              fontFamily: 'var(--font-body)',
              whiteSpace: 'pre-wrap',
              minHeight: 280,
              margin: 0,
              lineHeight: 1.7,
            }}>{template.target}</pre>
          </div>
        </div>
        {template.linkUrl && (
          <div style={{ marginTop: 14, padding: 12, background: 'var(--navy-50)', borderRadius: 8, fontSize: 13 }}>
            <Icon name="link" size={12} style={{ verticalAlign: 'middle' }}/>{' '}
            Prepared document: <a href={template.linkUrl} target="_blank" rel="noopener" style={{ color: 'var(--navy-700)' }}>{template.linkUrl}</a>
          </div>
        )}
      </div>

      {showEdit && (
        <TemplateModal
          template={template}
          onClose={() => setShowEdit(false)}
          onSaved={() => setShowEdit(false)}
        />
      )}
    </div>
  );
}

function TemplateModal({ template, onClose, onSaved }) {
  const [form, setForm] = useState({
    title: template?.title || '',
    sourceLang: template?.sourceLang || 'Lao',
    targetLang: template?.targetLang || 'English',
    source: template?.source || '',
    target: template?.target || '',
    linkUrl: template?.linkUrl || '',
  });

  const handleSave = () => {
    if (!form.title.trim()) { alert('Title is required'); return; }
    if (template) {
      window.PVStore.updateTranslationTemplate(template.id, form);
      onSaved && onSaved(template.id);
    } else {
      const t = window.PVStore.addTranslationTemplate(form);
      onSaved && onSaved(t.id);
    }
  };

  return (
    <Modal
      open
      onClose={onClose}
      title={template ? 'Edit template' : 'New template'}
      size="lg"
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={handleSave}>{template ? 'Save' : 'Create'}</button>
      </>}
    >
      <div className="row-gap">
        <div className="field">
          <label>Title</label>
          <input value={form.title} onChange={e=>setForm({...form, title: e.target.value})} placeholder="e.g. Birth Certificate (LA → EN)"/>
        </div>
        <div className="form-row two">
          <div className="field">
            <label>Source language</label>
            <input value={form.sourceLang} onChange={e=>setForm({...form, sourceLang: e.target.value})}/>
          </div>
          <div className="field">
            <label>Target language</label>
            <input value={form.targetLang} onChange={e=>setForm({...form, targetLang: e.target.value})}/>
          </div>
        </div>
        <div className="form-row two">
          <div className="field">
            <label>Source ({form.sourceLang}) template</label>
            <textarea
              value={form.source}
              onChange={e=>setForm({...form, source: e.target.value})}
              rows="10"
              style={{ fontFamily: 'var(--font-lao)', lineHeight: 1.6 }}
              placeholder="Source document template…"
            />
          </div>
          <div className="field">
            <label>Translation ({form.targetLang}) template</label>
            <textarea
              value={form.target}
              onChange={e=>setForm({...form, target: e.target.value})}
              rows="10"
              style={{ lineHeight: 1.6 }}
              placeholder="Translated document template…"
            />
          </div>
        </div>
        <div className="field">
          <label>Link to prepared document (optional)</label>
          <input
            value={form.linkUrl}
            onChange={e=>setForm({...form, linkUrl: e.target.value})}
            placeholder="https://drive.google.com/… or file path"
          />
          <div className="hint">Useful for keeping a link to the live Word/Drive doc your team edits.</div>
        </div>
      </div>
    </Modal>
  );
}

window.TemplatesView = TemplatesView;
