// settings.jsx — right rail, contextual to the selected block

const BRAND_SWATCHES = ['#0A6E6E','#185FA5','#ffffff','#1a1918','#f5f4f1','#F5A623'];

function FieldSection({ label }) {
  return <div className="bld-field-section">{label}</div>;
}

async function handleImageUpload(e, update) {
  const file = e.target.files[0];
  if (!file) return;
  const cfg = window.TMS_CONFIG || {};
  const workerUrl = (cfg.workerUrl || 'https://tms-promotions-api.tms-travel-marketing-systems.workers.dev').replace(/\/$/, '');
  const agentToken = cfg.agentToken || '';
  update('uploading...');
  const formData = new FormData();
  formData.append('file', file);
  formData.append('folder', 'tms-email-images');
  try {
    const headers = agentToken ? { 'Authorization': 'Bearer ' + agentToken } : {};
    const res = await fetch(workerUrl + '/cloudinary/upload', { method: 'POST', headers, body: formData });
    const data = await res.json();
    if (data.secure_url) {
      update(data.secure_url);
    } else {
      update('');
      alert('Upload failed — ' + (data.error?.message || data.error || 'unknown error'));
    }
  } catch(err) {
    update('');
    alert('Upload failed — ' + err.message);
  }
  e.target.value = '';
}

async function handleLogoUpload(e, update) {
  const file = e.target.files[0];
  if (!file) return;
  const cfg = window.TMS_CONFIG || {};
  const workerUrl = (cfg.workerUrl || 'https://tms-promotions-api.tms-travel-marketing-systems.workers.dev').replace(/\/$/, '');
  const agentToken = cfg.agentToken || '';
  update('uploading...');
  const formData = new FormData();
  formData.append('file', file);
  formData.append('folder', 'tms-logos');
  try {
    const headers = agentToken ? { 'Authorization': 'Bearer ' + agentToken } : {};
    const res = await fetch(workerUrl + '/cloudinary/upload', { method: 'POST', headers, body: formData });
    const data = await res.json();
    if (data.secure_url) {
      update(data.secure_url);
    } else {
      update('');
      alert('Upload failed — ' + (data.error?.message || data.error || 'unknown error'));
    }
  } catch(err) {
    update('');
    alert('Upload failed — ' + err.message);
  }
  e.target.value = '';
}

function ColorPicker({ label, value, onChange }) {
  const inputId = 'cp-' + label.replace(/\s+/g, '-').replace(/[^a-zA-Z0-9-]/g, '');
  const safeHex = /^#[0-9A-Fa-f]{6}$/.test(value) ? value : '#ffffff';
  return (
    <div className="bld-field">
      <label>{label}</label>
      <div style={{display:'flex', alignItems:'center', gap:'8px'}}>
        <div style={{position:'relative', flexShrink:0}}>
          <div
            style={{
              width:'32px', height:'32px', borderRadius:'6px',
              background: value || '#ffffff',
              border:'1px solid var(--product-border)',
              cursor:'pointer', flexShrink:0,
            }}
            onClick={() => document.getElementById(inputId).click()}
          />
          <input
            id={inputId}
            type="color"
            value={safeHex}
            onChange={e => onChange(e.target.value)}
            style={{position:'absolute', opacity:0, width:0, height:0, pointerEvents:'none'}}
          />
        </div>
        <input
          type="text"
          value={value || ''}
          onChange={e => {
            const v = e.target.value;
            if (/^#[0-9A-Fa-f]{0,6}$/.test(v)) onChange(v);
          }}
          onBlur={e => {
            if (/^#[0-9A-Fa-f]{3}$/.test(e.target.value)) {
              const s = e.target.value.slice(1);
              onChange('#' + s[0]+s[0]+s[1]+s[1]+s[2]+s[2]);
            }
          }}
          placeholder="#000000"
          className="bld-input"
          style={{flex:1, fontFamily:'var(--font-mono)', fontSize:'13px'}}
          maxLength={7}
        />
        <div style={{display:'flex', gap:'4px', flexShrink:0}}>
          {BRAND_SWATCHES.map(c => (
            <div
              key={c}
              onClick={() => onChange(c)}
              title={c}
              style={{
                width:'18px', height:'18px', borderRadius:'3px',
                background: c,
                border: value === c ? '2px solid var(--product-fg)' : '1px solid var(--product-border)',
                cursor:'pointer', flexShrink:0,
              }}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <div className="bld-field">
      <label>{label}</label>
      {children}
      {hint ? <div className="bld-field-hint">{hint}</div> : null}
    </div>
  );
}

function TextInput({ value, onChange, placeholder, type }) {
  return <input className="bld-input" type={type || "text"} value={value || ""} placeholder={placeholder || ""}
                onChange={(e) => onChange(e.target.value)} />;
}

function ImageUploadField({ label, hint, value, onChange, isMobile }) {
  return (
    <Field label={label} hint={hint}>
      <TextInput type="url" value={value} onChange={onChange} placeholder="https://…" />
      <label style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        gap: '7px', padding: '9px', marginTop: '4px',
        border: '1px dashed var(--product-border)', borderRadius: '8px',
        cursor: 'pointer', fontSize: '12px', color: 'var(--product-fg-muted)',
        background: 'var(--product-bg)', userSelect: 'none',
      }}>
        <input
          type="file"
          accept="image/*"
          capture={isMobile ? "environment" : undefined}
          style={{ display: 'none' }}
          onChange={e => handleImageUpload(e, onChange)}
        />
        📷 {isMobile ? 'Take photo or choose from library' : 'Upload image'}
      </label>
      {value && value !== 'uploading...' && (
        <img src={value} alt="Preview"
          style={{ marginTop: '6px', width: '100%', maxHeight: '120px', objectFit: 'cover', borderRadius: '6px', border: '1px solid var(--product-border)' }}
          onError={e => { e.target.style.display = 'none'; }} />
      )}
      {value === 'uploading...' && (
        <div style={{ marginTop: '4px', fontSize: 11, color: 'var(--product-fg-muted)' }}>Uploading…</div>
      )}
    </Field>
  );
}

function SettingsPanel({ block, onChange, isMobile }) {
  const { MousePointer } = window.Icons;
  if (!block) {
    return (
      <aside className="bld-settings">
        <div className="bld-settings-empty">
          <MousePointer />
          <p>Select a block on the canvas to edit its content and styling.</p>
        </div>
      </aside>
    );
  }
  const p = block.props;
  const set = (k) => (v) => onChange(block.id, k, v);
  const setSocial = (k) => (v) => onChange(block.id, 'socials', { ...(p.socials || {}), [k]: v });
  const meta = window.TYPE_META[block.type];
  const Ic = window.Icons[meta.label];

  return (
    <aside className="bld-settings">
      <div className="bld-settings-head">
        <span className="bld-set-ic"><Ic /></span>
        <div>
          <h2>{meta.settings}</h2>
          <div className="bld-set-sub">{meta.label} block</div>
        </div>
      </div>
      <div className="bld-settings-body">

        {block.type === "header" && (<>
          <FieldSection label="Branding" />
          <Field label="Logo image URL">
            <div style={{display:'flex', gap:'6px', alignItems:'center'}}>
              <input
                type="text"
                value={p.logoUrl || ''}
                onChange={e => set("logoUrl")(e.target.value)}
                placeholder="https://…"
                className="bld-input"
                style={{flex:1, fontSize:13}}
              />
              <button
                className="bld-btn"
                onClick={() => document.getElementById('logo-upload-input').click()}
                title="Upload logo"
                style={{flexShrink:0, padding:'5px 8px', fontSize:12}}
              >↑ Upload</button>
              <input
                id="logo-upload-input"
                type="file"
                accept="image/png,image/jpeg,image/svg+xml,image/gif"
                style={{display:'none'}}
                onChange={e => handleLogoUpload(e, set("logoUrl"))}
              />
            </div>
            {p.logoUrl && p.logoUrl !== 'uploading...' && (
              <div style={{marginTop:'6px'}}>
                <img
                  src={p.logoUrl}
                  alt="Logo preview"
                  style={{maxHeight:'40px', maxWidth:'100%', borderRadius:'4px', border:'1px solid var(--product-border)'}}
                  onError={e => { e.target.style.display = 'none'; }}
                />
              </div>
            )}
            {p.logoUrl === 'uploading...' && (
              <div style={{marginTop:'4px', fontSize:11, color:'var(--product-fg-muted)'}}>Uploading…</div>
            )}
          </Field>
          <Field label="Company name" hint="Shown when no logo URL is set"><TextInput value={p.logoText || p.brand} onChange={set("logoText")} placeholder="TMS Travel Marketing" /></Field>
          <Field label="Tagline"><TextInput value={p.tagline} onChange={set("tagline")} placeholder="Your trusted travel experts" /></Field>
          <FieldSection label="Contact" />
          <Field label="Phone number" hint="Leave empty to hide"><TextInput value={p.phone} onChange={set("phone")} placeholder="01234 567890" /></Field>
          <FieldSection label="Colours" />
          <ColorPicker label="Background" value={p.bgColor || '#0A6E6E'} onChange={set("bgColor")} />
          <ColorPicker label="Text colour" value={p.textColor || '#ffffff'} onChange={set("textColor")} />
          <FieldSection label="Social media" />
          <Field label="Facebook"><TextInput value={(p.socials || {}).facebook} onChange={setSocial("facebook")} placeholder="page name or full URL" /></Field>
          <Field label="Instagram"><TextInput value={(p.socials || {}).instagram} onChange={setSocial("instagram")} placeholder="username or full URL" /></Field>
          <Field label="WhatsApp"><TextInput value={(p.socials || {}).whatsapp} onChange={setSocial("whatsapp")} placeholder="447700900000" /></Field>
          <Field label="LinkedIn"><TextInput value={(p.socials || {}).linkedin} onChange={setSocial("linkedin")} placeholder="profile name or full URL" /></Field>
        </>)}

        {block.type === "offer" && (<>
          <Field label="Destination"><TextInput value={p.destination} onChange={set("destination")} placeholder="Maldives" /></Field>
          <Field label="Offer headline"><TextInput value={p.headline} onChange={set("headline")} placeholder="7 nights all-inclusive" /></Field>
          <Field label="Price"><TextInput value={p.price} onChange={set("price")} placeholder="£1,299pp" /></Field>
          <Field label="Badge text"><TextInput value={p.badge} onChange={set("badge")} placeholder="ATOL Protected" /></Field>
          <Field label="Availability note"><TextInput value={p.availability} onChange={set("availability")} placeholder="Limited availability" /></Field>
          <ImageUploadField label="Image" hint="Leave empty to show a placeholder" value={p.imageUrl} onChange={set("imageUrl")} isMobile={isMobile} />
          <Field label="Button text"><TextInput value={p.buttonText} onChange={set("buttonText")} placeholder="View this offer" /></Field>
          <ColorPicker label="Button colour" value={p.buttonColor || '#0E8A99'} onChange={set("buttonColor")} />
          <Field label="Operator" hint="Required for DMCC Act 2024 compliance."><TextInput value={p.operator} onChange={set("operator")} placeholder="e.g. TUI, Jet2holidays" /></Field>
          <Field label="Button link URL"><TextInput type="url" value={p.ctaUrl} onChange={set("ctaUrl")} placeholder="https://latecards.co.uk/…" /></Field>
        </>)}

        {block.type === "cruise" && (<>
          <Field label="Cruise name"><TextInput value={p.cruiseName} onChange={set("cruiseName")} placeholder="Mediterranean Discovery" /></Field>
          <Field label="Operator & ship"><TextInput value={p.operatorLine} onChange={set("operatorLine")} placeholder="MSC Cruises · MSC Bellissima" /></Field>
          <Field label="Departure date"><TextInput value={p.departureDate} onChange={set("departureDate")} placeholder="6 Jun 2026" /></Field>
          <Field label="Duration (nights)"><TextInput value={p.duration} onChange={set("duration")} placeholder="7" /></Field>
          <Field label="Departure port"><TextInput value={p.departurePort} onChange={set("departurePort")} placeholder="Southampton" /></Field>
          <Field label="Regions"><TextInput value={p.regions} onChange={set("regions")} placeholder="Mediterranean" /></Field>
          <Field label="Price"><TextInput value={p.price} onChange={set("price")} placeholder="From £899pp" /></Field>
          <ImageUploadField label="Image" hint="Leave empty to show a placeholder" value={p.imageUrl} onChange={set("imageUrl")} isMobile={isMobile} />
          <Field label="Teaser text" hint="Brief highlight from the cruise description.">
            <textarea className="bld-input" value={p.teaser || ""} onChange={(e) => set("teaser")(e.target.value)} rows={3} />
          </Field>
          <Field label="Promo badge" hint="Leave empty to hide."><TextInput value={p.promoBadge} onChange={set("promoBadge")} placeholder="Special offer" /></Field>
          <ColorPicker label="CTA colour" value={p.ctaColor || '#0A6E7E'} onChange={set("ctaColor")} />
          <Field label="Cruise detail link" hint="Populated automatically from search — override if needed."><TextInput type="url" value={p.ctaUrl} onChange={set("ctaUrl")} placeholder="https://…" /></Field>
        </>)}

        {block.type === "text" && (
          <Field label="Body text" hint="Basic HTML — <strong> and <a> are supported.">
            <textarea className="bld-input" value={p.html || ""} onChange={(e) => set("html")(e.target.value)} rows={6} />
          </Field>
        )}

        {block.type === "image" && (<>
          <ImageUploadField label="Image" hint="Leave empty to show a placeholder" value={p.imageUrl} onChange={set("imageUrl")} isMobile={isMobile} />
          <Field label="Alt text" hint="Shown if the image can't load."><TextInput value={p.alt} onChange={set("alt")} placeholder="Describe the image" /></Field>
        </>)}

        {block.type === "video" && (<>
          <ImageUploadField label="Thumbnail" hint="Upload or paste a URL for the preview image" value={p.thumbUrl} onChange={set("thumbUrl")} isMobile={isMobile} />
          <Field label="Video title"><TextInput value={p.title} onChange={set("title")} placeholder="Watch the destination film" /></Field>
          <Field label="Video link URL"><TextInput type="url" value={p.link} onChange={set("link")} placeholder="https://…" /></Field>
        </>)}

        {block.type === "footer" && (<>
          <Field label="Company name"><TextInput value={p.company} onChange={set("company")} placeholder="Travel Marketing Systems Ltd" /></Field>
          <Field label="Address"><TextInput value={p.address} onChange={set("address")} placeholder="123 High Street, London, UK" /></Field>
          <FieldSection label="Colours" />
          <ColorPicker label="Background" value={p.bgColor || '#F0F1F4'} onChange={set("bgColor")} />
          <ColorPicker label="Text colour" value={p.textColor || '#4D4A44'} onChange={set("textColor")} />
          <Field label="Footer links" hint="Unsubscribe · View in browser · Privacy are added automatically.">
            <div className="bld-field-hint" style={{ paddingTop: 2 }}>Standard compliance links are included on every send.</div>
          </Field>
        </>)}

      </div>
    </aside>
  );
}

window.SettingsPanel = SettingsPanel;
