// Shared primitives — SVG icons, dividers, placeholder panels

const DrawnRule = ({ className = '', width = 120, color = 'currentColor' }) => (
  <svg
    className={`hand-accent ${className}`}
    width={width}
    height='8'
    viewBox='0 0 120 8'
    fill='none'
    style={{ display: 'block' }}
  >
    <path
      d='M1 4.2 C 20 2.5, 40 5.8, 60 3.9 S 100 2.2, 119 4.1'
      stroke={color}
      strokeWidth='1.4'
      strokeLinecap='round'
      fill='none'
    />
  </svg>
);

const DrawnArrow = ({ className = '', size = 42, color = 'currentColor' }) => (
  <svg
    className={`hand-accent ${className}`}
    width={size}
    height={size * 0.5}
    viewBox='0 0 84 42'
    fill='none'
  >
    <path
      d='M3 24 C 18 10, 38 6, 58 12 S 78 24, 80 24'
      stroke={color}
      strokeWidth='1.6'
      fill='none'
      strokeLinecap='round'
    />
    <path
      d='M70 16 L 80 24 L 72 31'
      stroke={color}
      strokeWidth='1.6'
      fill='none'
      strokeLinecap='round'
      strokeLinejoin='round'
    />
  </svg>
);

const DrawnCircle = ({ className = '', size = 80, color = 'currentColor' }) => (
  <svg
    className={`hand-accent ${className}`}
    width={size}
    height={size * 0.55}
    viewBox='0 0 180 100'
    fill='none'
    style={{ display: 'block' }}
  >
    <path
      d='M 20 50 C 20 30, 60 18, 90 18 S 160 28, 160 52 S 120 84, 90 84 S 22 74, 20 50 Z'
      stroke={color}
      strokeWidth='1.6'
      fill='none'
    />
  </svg>
);

// A sage-stroked topographic-line decoration — echoes the mountains in the logo
const TopoLines = ({ w = 600, h = 180, opacity = 0.25, color = '#7A8968' }) => (
  <svg width={w} height={h} viewBox='0 0 600 180' style={{ opacity, display: 'block' }} fill='none'>
    <path
      d='M0 140 C 80 120, 150 110, 230 120 S 380 150, 460 130 S 560 110, 600 120'
      stroke={color}
      strokeWidth='1'
    />
    <path
      d='M0 115 C 90 90, 170 80, 260 95 S 400 125, 480 100 S 580 80, 600 90'
      stroke={color}
      strokeWidth='1'
    />
    <path
      d='M0 90 C 100 60, 190 55, 290 70 S 420 105, 500 75 S 590 55, 600 65'
      stroke={color}
      strokeWidth='1'
    />
    <path
      d='M0 65 C 110 35, 220 30, 320 45 S 440 85, 520 55 S 595 35, 600 42'
      stroke={color}
      strokeWidth='1'
    />
  </svg>
);

// simple mountains echoing the logo
const LogoMountains = ({ w = 240, h = 80, color = '#7A8968' }) => (
  <svg width={w} height={h} viewBox='0 0 240 80' fill='none' style={{ display: 'block' }}>
    <path
      d='M0 68 L 28 44 L 42 58 L 64 30 L 92 68 L 0 68 Z'
      stroke={color}
      strokeWidth='1.2'
      fill='none'
    />
    <path
      d='M120 68 L 150 48 L 162 58 L 180 36 L 210 68 L 120 68 Z'
      stroke={color}
      strokeWidth='1.2'
      fill='none'
    />
    <circle cx='196' cy='32' r='8' fill='#C98862' opacity='0.65' />
  </svg>
);

// Photo placeholder with striped treatment + monospace caption
const PhotoPlaceholder = ({
  label = 'photo',
  ratio = '4/3',
  tone = 'warm',
  className = '',
  style = {},
}) => {
  const isSage = tone === 'sage';
  const bg = isSage ? 'var(--sage-soft)' : 'var(--paper-dark)';
  const stripe = isSage ? 'rgba(93,107,79,0.25)' : 'rgba(58,46,36,0.14)';
  return (
    <div
      className={className}
      style={{
        aspectRatio: ratio,
        background: bg,
        backgroundImage: `repeating-linear-gradient(135deg, ${stripe} 0 1px, transparent 1px 14px)`,
        position: 'relative',
        overflow: 'hidden',
        border: '1px solid rgba(58,46,36,0.12)',
        ...style,
      }}
    >
      <div
        style={{
          position: 'absolute',
          left: 12,
          bottom: 10,
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
          fontSize: 10,
          letterSpacing: '0.1em',
          textTransform: 'uppercase',
          color: 'var(--ink-soft)',
          opacity: 0.75,
          background: 'rgba(244,239,230,0.85)',
          padding: '2px 7px',
        }}
      >
        {label}
      </div>
    </div>
  );
};

// Lead form — used in both hero variants
// Replace this URL with your Google Apps Script web app URL
const GOOGLE_SCRIPT_URL =
  'https://script.google.com/macros/s/AKfycbzQsYeePiaITfBjGNj9j9sSnSGIUh2lo3Fcoo4ImYasickPjck7NYd_7LsvUNIAwwMM6w/exec';

const LeadForm = ({ layout = 'stacked', compact = false }) => {
  const [vals, setVals] = React.useState({ first: '', last: '', phone: '', email: '', notes: '' });
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState('');
  const [errors, setErrors] = React.useState({});

  const validate = () => {
    const e = {};
    if (!vals.first.trim()) e.first = 'Please enter your first name';
    if (!vals.last.trim()) e.last = 'Please enter your last name';
    if (!vals.phone.trim()) {
      e.phone = 'Please enter your phone number';
    } else if (!/^[\d\s\-\(\)\+\.]{10,}$/.test(vals.phone)) {
      e.phone = 'Please enter a valid phone number';
    }
    if (!vals.email.trim()) {
      e.email = 'Please enter your email address';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(vals.email)) {
      e.email = 'Please enter a valid email address';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const onSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;

    setSubmitting(true);
    setSubmitError('');

    try {
      await fetch(GOOGLE_SCRIPT_URL, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(vals),
      });
      setSubmitted(true);
    } catch (err) {
      setSubmitError('Something went wrong. Please try again or call us directly.');
    } finally {
      setSubmitting(false);
    }
  };
  const set = (k) => (e) => {
    setVals((v) => ({ ...v, [k]: e.target.value }));
    if (errors[k]) setErrors((err) => ({ ...err, [k]: null }));
  };

  const inputStyle = (err) => ({
    width: '100%',
    padding: compact ? '11px 13px' : '14px 14px',
    border: `1px solid ${err ? 'var(--terra-dark)' : 'rgba(58,46,36,0.25)'}`,
    background: 'rgba(255,253,248,0.92)',
    color: 'var(--ink)',
    borderRadius: 2,
    outline: 'none',
    fontSize: compact ? 14 : 15,
    fontFamily: 'var(--f-body)',
  });
  const labelStyle = {
    display: 'block',
    fontSize: 11,
    letterSpacing: '0.16em',
    textTransform: 'uppercase',
    color: 'var(--ink-soft)',
    marginBottom: 6,
    fontWeight: 600,
  };
  const errorStyle = {
    fontSize: 12,
    color: 'var(--terra-dark)',
    marginTop: 4,
  };

  const successStyle = {
    fontSize: 14,
    color: '#15803d',
    marginTop: 12,
    padding: '14px 18px',
    background: 'rgba(34, 197, 94, 0.15)',
    border: '1px solid #22c55e',
    borderRadius: 2,
    fontWeight: 500,
  };

  const gridCols = layout === 'row' ? 'repeat(4, 1fr) auto' : 'repeat(2, 1fr)';
  return (
    <form
      onSubmit={onSubmit}
      className={layout === 'row' ? 'lead-form-row' : ''}
      style={{ display: 'grid', gridTemplateColumns: gridCols, gap: compact ? 10 : 14 }}
    >
      <div>
        <label style={labelStyle}>First name</label>
        <input
          style={inputStyle(errors.first)}
          value={vals.first}
          onChange={set('first')}
          placeholder=''
        />
        {errors.first && <div style={errorStyle}>{errors.first}</div>}
      </div>
      <div>
        <label style={labelStyle}>Last name</label>
        <input
          style={inputStyle(errors.last)}
          value={vals.last}
          onChange={set('last')}
          placeholder=''
        />
        {errors.last && <div style={errorStyle}>{errors.last}</div>}
      </div>
      <div>
        <label style={labelStyle}>Phone</label>
        <input
          style={inputStyle(errors.phone)}
          value={vals.phone}
          onChange={set('phone')}
          placeholder='(555) 123-4567'
        />
        {errors.phone && <div style={errorStyle}>{errors.phone}</div>}
      </div>
      <div>
        <label style={labelStyle}>Email</label>
        <input
          style={inputStyle(errors.email)}
          value={vals.email}
          onChange={set('email')}
          placeholder='you@example.com'
        />
        {errors.email && <div style={errorStyle}>{errors.email}</div>}
      </div>
      <div style={{ gridColumn: '1 / -1' }}>
        <label style={labelStyle}>
          Additional information{' '}
          <span
            style={{
              fontWeight: 400,
              letterSpacing: 0,
              textTransform: 'none',
              fontSize: 11,
              color: 'var(--ink-mute)',
            }}
          >
            — optional
          </span>
        </label>
        <textarea
          value={vals.notes}
          onChange={set('notes')}
          placeholder=''
          rows={3}
          style={{ ...inputStyle(false), resize: 'vertical', lineHeight: 1.5 }}
        />
      </div>
      <div style={{ gridColumn: '1 / -1', alignSelf: 'end' }}>
        <button
          type='submit'
          disabled={submitting}
          style={{
            width: '100%',
            padding: compact ? '12px 22px' : '15px 26px',
            background: 'var(--ink)',
            color: 'var(--paper)',
            border: 'none',
            borderRadius: 2,
            fontSize: 14,
            fontWeight: 600,
            letterSpacing: '0.14em',
            textTransform: 'uppercase',
            fontFamily: 'var(--f-body)',
            whiteSpace: 'nowrap',
            cursor: submitting ? 'default' : 'pointer',
            opacity: submitting ? 0.7 : 1,
          }}
        >
          {submitting ? 'Submitting...' : 'Submit'}
        </button>
        {submitted && (
          <div style={successStyle}>
            Thanks for reaching out! We try our best give you a call within one business day.
          </div>
        )}
        {submitError && (
          <div
            style={{
              fontSize: 14,
              color: 'var(--terra-dark)',
              marginTop: 12,
              padding: '14px 18px',
              background: 'rgba(201, 136, 98, 0.15)',
              border: '1px solid var(--terra)',
              borderRadius: 2,
            }}
          >
            {submitError}
          </div>
        )}
      </div>
      {!submitted && (
        <div style={{ gridColumn: '1 / -1', fontSize: 12, color: 'var(--ink-mute)', marginTop: 2 }}>
          Free valuation · No obligation
        </div>
      )}
    </form>
  );
};

Object.assign(window, {
  DrawnRule,
  DrawnArrow,
  DrawnCircle,
  TopoLines,
  LogoMountains,
  PhotoPlaceholder,
  LeadForm,
});
