// Cards.jsx — Reusable farm listing card components

const CATEGORY_COLORS = {
  "Pumpkin Patch":       { bg: "#F5DDD0", accent: "#C8622A", text: "#7A2E00" },
  "Apple Orchard":       { bg: "#D8E8D0", accent: "#4A7340", text: "#1E3D18" },
  "Flower Farm":         { bg: "#F5E4C0", accent: "#C4922A", text: "#6B4A00" },
  "Berry Farm":          { bg: "#E8D5F0", accent: "#7C3AED", text: "#3D1A6E" },
  "Corn Maze":           { bg: "#FFF0C0", accent: "#C4922A", text: "#5C3D00" },
  "Christmas Tree Farm": { bg: "#D0EAD8", accent: "#15803D", text: "#0A3D1E" },
};

const CATEGORY_PATTERNS = {
  "Pumpkin Patch": (colors) => (
    <svg viewBox="0 0 320 200" xmlns="http://www.w3.org/2000/svg" style={{width:'100%',height:'100%'}}>
      <rect width="320" height="200" fill={colors.bg}/>
      {/* Sky */}
      <rect width="320" height="120" fill="#F5E0C8"/>
      {/* Ground */}
      <rect y="120" width="320" height="80" fill="#B8954A"/>
      {/* Field rows */}
      {[130,145,160,175].map((y,i) => (
        <ellipse key={i} cx="160" cy={y} rx={140+i*10} ry="4" fill="rgba(100,70,20,0.12)"/>
      ))}
      {/* Pumpkins */}
      {[[60,118],[120,122],[180,116],[240,120],[90,140],[160,138],[220,142],[50,158],[140,154],[200,156],[270,150]].map(([x,y],i) => (
        <g key={i}>
          <ellipse cx={x} cy={y} rx="11" ry="9" fill="#C8622A"/>
          <ellipse cx={x-5} cy={y} rx="7" ry="8.5" fill="#D97740" opacity="0.6"/>
          <ellipse cx={x+5} cy={y} rx="7" ry="8.5" fill="#B05520" opacity="0.5"/>
          <line x1={x} y1={y-9} x2={x+3} y2={y-14} stroke="#4A7340" strokeWidth="1.5" strokeLinecap="round"/>
          <path d={`M${x+3} ${y-14} Q${x+8} ${y-18} ${x+6} ${y-12}`} stroke="#4A7340" strokeWidth="1" fill="none"/>
        </g>
      ))}
      {/* Sun */}
      <circle cx="270" cy="35" r="22" fill="#F5C842" opacity="0.7"/>
      <circle cx="270" cy="35" r="16" fill="#F5D860"/>
      {/* Barn */}
      <rect x="230" y="70" width="50" height="40" fill="#8B3A2A"/>
      <polygon points="230,70 280,70 255,50" fill="#6B2A1A"/>
      <rect x="248" y="88" width="14" height="22" fill="#5C2010"/>
      <rect x="232" y="74" width="12" height="12" fill="#F5C842" opacity="0.5"/>
      {/* Fence */}
      {[20,35,50,65,80,95,110].map(x => (
        <g key={x}>
          <rect x={x} y="112" width="3" height="14" fill="#D4A87A" rx="1"/>
          <rect x={x-2} y="114" width="16" height="2" fill="#D4A87A" rx="1"/>
          <rect x={x-2} y="120" width="16" height="2" fill="#D4A87A" rx="1"/>
        </g>
      ))}
    </svg>
  ),
  "Apple Orchard": (colors) => (
    <svg viewBox="0 0 320 200" xmlns="http://www.w3.org/2000/svg" style={{width:'100%',height:'100%'}}>
      <rect width="320" height="200" fill="#E8F0E0"/>
      <rect width="320" height="130" fill="#D0E4C8"/>
      <rect y="130" width="320" height="70" fill="#8B6F3A"/>
      {/* Tree rows */}
      {[[50,85],[130,90],[210,85],[290,90],[30,120],[110,115],[190,120],[270,115]].map(([x,y],i) => (
        <g key={i}>
          <rect x={x-3} y={y} width="6" height={200-y-40} fill="#6B4A20"/>
          <ellipse cx={x} cy={y-10} rx="28" ry="32" fill="#3A7D44"/>
          <ellipse cx={x-8} cy={y-5} rx="20" ry="24" fill="#4A8D50" opacity="0.7"/>
          {/* Apples */}
          {[[x-10,y-18],[x+8,y-22],[x-4,y-30],[x+12,y-10],[x-14,y-8]].slice(0,3+i%2).map(([ax,ay],j) => (
            <g key={j}>
              <circle cx={ax} cy={ay} r="5" fill="#D42A2A"/>
              <circle cx={ax} cy={ay} r="4" fill="#E83A3A"/>
              <line x1={ax} y1={ay-5} x2={ax+2} y2={ay-8} stroke="#2A5A20" strokeWidth="1.2" strokeLinecap="round"/>
            </g>
          ))}
        </g>
      ))}
      {/* Clouds */}
      <ellipse cx="80" cy="25" rx="35" ry="16" fill="white" opacity="0.7"/>
      <ellipse cx="95" cy="22" rx="25" ry="14" fill="white" opacity="0.7"/>
      <ellipse cx="230" cy="18" rx="28" ry="13" fill="white" opacity="0.6"/>
      {/* Baskets */}
      {[[80,148],[160,145],[240,148]].map(([x,y],i) => (
        <g key={i}>
          <ellipse cx={x} cy={y+8} rx="12" ry="4" fill="#8B6030" opacity="0.4"/>
          <rect x={x-10} y={y-2} width="20" height="14" rx="2" fill="#C4882A"/>
          <ellipse cx={x} cy={y-2} rx="10" ry="4" fill="#E8A840"/>
          <circle cx={x-3} cy={y-4} r="3" fill="#D42A2A"/>
          <circle cx={x+4} cy={y-5} r="3" fill="#D42A2A"/>
        </g>
      ))}
      <text x="160" y="186" textAnchor="middle" fontFamily="serif" fontSize="11" fill="rgba(80,50,20,0.5)" fontStyle="italic">apple orchard</text>
    </svg>
  ),
  "Flower Farm": (colors) => (
    <svg viewBox="0 0 320 200" xmlns="http://www.w3.org/2000/svg" style={{width:'100%',height:'100%'}}>
      <rect width="320" height="200" fill="#FFF8E8"/>
      <rect y="140" width="320" height="60" fill="#8B9A50"/>
      {/* Sky gradient */}
      <defs>
        <linearGradient id="skyGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#C8DEFF" stopOpacity="0.5"/>
          <stop offset="100%" stopColor="#FFF8E8" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <rect width="320" height="140" fill="url(#skyGrad)"/>
      {/* Flower rows */}
      {[0,1,2,3,4].map(row => (
        Array.from({length: 12}, (_,col) => {
          const x = 14 + col * 26 + (row%2)*12;
          const y = 80 + row * 16;
          const colors2 = ['#F5C842','#E87040','#E879A0','#A855F7','#F5C842','#60A0E0'][( row*3+col)%6];
          return (
            <g key={`${row}-${col}`}>
              <line x1={x} y1={y+8} x2={x} y2={y+24} stroke="#4A7A30" strokeWidth="1.5"/>
              {/* petals */}
              {[0,60,120,180,240,300].map(angle => (
                <ellipse key={angle}
                  cx={x + Math.cos(angle*Math.PI/180)*7}
                  cy={y + Math.sin(angle*Math.PI/180)*7}
                  rx="5" ry="3"
                  fill={colors2} opacity="0.9"
                  transform={`rotate(${angle}, ${x + Math.cos(angle*Math.PI/180)*7}, ${y + Math.sin(angle*Math.PI/180)*7})`}
                />
              ))}
              <circle cx={x} cy={y} r="4.5" fill="#F5E842" opacity="0.9"/>
              <circle cx={x} cy={y} r="3" fill="#FFD700"/>
            </g>
          );
        })
      ))}
      {/* Barn in bg */}
      <rect x="255" y="55" width="50" height="70" fill="#C8622A" opacity="0.35"/>
      <polygon points="255,55 305,55 280,35" fill="#8B3A1A" opacity="0.35"/>
      <text x="160" y="190" textAnchor="middle" fontFamily="serif" fontSize="11" fill="rgba(60,40,10,0.4)" fontStyle="italic">flower farm</text>
    </svg>
  ),
  "Berry Farm": (colors) => (
    <svg viewBox="0 0 320 200" xmlns="http://www.w3.org/2000/svg" style={{width:'100%',height:'100%'}}>
      <rect width="320" height="200" fill="#EEE8F5"/>
      <rect y="130" width="320" height="70" fill="#7A7A3A"/>
      {/* Sky */}
      <rect width="320" height="130" fill="#DDD5F0"/>
      {/* Rows of berry bushes */}
      {[0,1,2,3].map(row => (
        Array.from({length: 7}, (_,col) => {
          const x = 24 + col * 42;
          const y = 82 + row * 14;
          const isBlueb = col % 2 === 0;
          return (
            <g key={`${row}-${col}`}>
              <ellipse cx={x} cy={y+8} rx="18" ry="10" fill={isBlueb ? "#3A5A20" : "#2A5A30"}/>
              <ellipse cx={x-5} cy={y+4} rx="12" ry="8" fill={isBlueb ? "#4A7A30" : "#3A7A40"} opacity="0.8"/>
              {/* Berries */}
              {[[-8,0],[-3,-4],[3,-2],[8,1],[-1,3],[5,-5]].map(([dx,dy],j) => (
                <circle key={j} cx={x+dx} cy={y+dy} r={isBlueb ? 4 : 3.5}
                  fill={isBlueb ? "#4A44C8" : "#E82850"}
                  opacity="0.9"
                />
              ))}
              {isBlueb && [[-8,0],[-3,-4],[3,-2],[8,1],[-1,3],[5,-5]].map(([dx,dy],j) => (
                <circle key={j} cx={x+dx} cy={y+dy} r="1.5" fill="rgba(255,255,255,0.3)"/>
              ))}
            </g>
          );
        })
      ))}
      <ellipse cx="70" cy="30" rx="40" ry="18" fill="white" opacity="0.5"/>
      <ellipse cx="240" cy="22" rx="32" ry="14" fill="white" opacity="0.4"/>
      <text x="160" y="190" textAnchor="middle" fontFamily="serif" fontSize="11" fill="rgba(50,30,80,0.4)" fontStyle="italic">berry farm</text>
    </svg>
  ),
  "Corn Maze": (colors) => (
    <svg viewBox="0 0 320 200" xmlns="http://www.w3.org/2000/svg" style={{width:'100%',height:'100%'}}>
      <rect width="320" height="200" fill="#FFF8D0"/>
      <rect y="120" width="320" height="80" fill="#A08020"/>
      {/* Aerial maze pattern */}
      <rect y="70" width="320" height="60" fill="#8B9A20" opacity="0.4"/>
      {/* Corn rows - vertical */}
      {Array.from({length: 22}, (_,i) => {
        const x = 8 + i*14;
        return (
          <g key={i}>
            {Array.from({length: 8}, (_,j) => {
              const y = 50 + j*10;
              return (
                <g key={j}>
                  <line x1={x} y1={y+2} x2={x} y2={y+9} stroke="#4A7A10" strokeWidth="2"/>
                  <ellipse cx={x} cy={y} rx="4" ry="6" fill="#5A8A18" opacity="0.8"/>
                  <ellipse cx={x-2} cy={y+1} rx="3" ry="4" fill="#6A9A20" opacity="0.5"/>
                  {j===3 && <ellipse cx={x} cy={y-2} rx="3" ry="5" fill="#D4A820" opacity="0.7"/>}
                </g>
              );
            })}
          </g>
        );
      })}
      {/* Maze paths overlay */}
      <rect x="40" y="55" width="240" height="80" fill="rgba(200,160,20,0.12)" rx="2"/>
      {/* Path lines */}
      {[
        "M60 70 L120 70 L120 90 L180 90 L180 70 L240 70",
        "M80 110 L140 110 L140 90",
        "M180 110 L220 110 L220 90",
        "M60 90 L80 90 L80 110",
        "M200 70 L200 90",
      ].map((d,i) => (
        <path key={i} d={d} stroke="rgba(200,160,20,0.5)" strokeWidth="6" fill="none" strokeLinecap="round"/>
      ))}
      {/* Entrance arrow */}
      <text x="30" y="138" fontFamily="serif" fontSize="10" fill="#8B6010" opacity="0.7">↓ ENTER</text>
      <text x="160" y="190" textAnchor="middle" fontFamily="serif" fontSize="11" fill="rgba(60,40,0,0.4)" fontStyle="italic">corn maze</text>
    </svg>
  ),
  "Christmas Tree Farm": (colors) => (
    <svg viewBox="0 0 320 200" xmlns="http://www.w3.org/2000/svg" style={{width:'100%',height:'100%'}}>
      <rect width="320" height="200" fill="#E8F4F0"/>
      <rect y="150" width="320" height="50" fill="#C8E0D8"/>
      {/* Snow ground */}
      <ellipse cx="160" cy="155" rx="170" ry="20" fill="white" opacity="0.7"/>
      {/* Sky */}
      <rect width="320" height="150" fill="#D0ECE8"/>
      {/* Stars */}
      {[[40,20],[100,12],[200,18],[270,8],[150,30]].map(([x,y],i) => (
        <polygon key={i} points={`${x},${y-5} ${x+2},${y-1} ${x+6},${y-1} ${x+3},${y+2} ${x+4},${y+6} ${x},${y+3} ${x-4},${y+6} ${x-3},${y+2} ${x-6},${y-1} ${x-2},${y-1}`}
          fill="#F5E860" opacity="0.6" transform={`scale(0.7, 0.7) translate(${x*0.43},${y*0.43})`}
        />
      ))}
      {/* Trees */}
      {[[50,130],[100,120],[155,125],[200,115],[250,130],[290,122],[30,145],[130,142],[180,145],[230,140],[275,145]].map(([x,y],i) => {
        const h = 40 + (i%3)*15;
        const w = h * 0.55;
        return (
          <g key={i}>
            <rect x={x-2} y={y} width="4" height="12" fill="#6B4A20"/>
            <polygon points={`${x},${y-h} ${x-w},${y} ${x+w},${y}`} fill={i%2===0 ? "#1A6030" : "#2A7840"}/>
            <polygon points={`${x},${y-h*0.7} ${x-w*0.8},${y-h*0.25} ${x+w*0.8},${y-h*0.25}`} fill={i%2===0 ? "#2A8040" : "#1A7030"}/>
            {/* Snow on branches */}
            <polygon points={`${x},${y-h*0.7} ${x-w*0.8},${y-h*0.25} ${x+w*0.8},${y-h*0.25}`} fill="white" opacity="0.25"/>
            <polygon points={`${x},${y-h} ${x-w},${y} ${x+w},${y}`} fill="white" opacity="0.15"/>
            {/* Star on top */}
            {i===4 && <polygon points={`${x},${y-h-8} ${x+2},${y-h-3} ${x+7},${y-h-3} ${x+3},${y-h} ${x+5},${y-h+5} ${x},${y-h+2} ${x-5},${y-h+5} ${x-3},${y-h} ${x-7},${y-h-3} ${x-2},${y-h-3}`} fill="#F5E840" opacity="0.9"/>}
          </g>
        );
      })}
      <text x="160" y="192" textAnchor="middle" fontFamily="serif" fontSize="11" fill="rgba(20,60,40,0.4)" fontStyle="italic">christmas tree farm</text>
    </svg>
  ),
};

const FarmImage = ({ listing, style = {}, srcOverride = null }) => {
  const colors = CATEGORY_COLORS[listing.category] || CATEGORY_COLORS["Pumpkin Patch"];
  const PatternFn = CATEGORY_PATTERNS[listing.category];
  const [broken, setBroken] = React.useState(false);
  const photo = srcOverride || (listing.images && listing.images[0]) || listing.image;
  React.useEffect(() => { setBroken(false); }, [photo]);

  // Show a real uploaded/linked photo when available; otherwise fall back to
  // the hand-drawn SVG scene for the category.
  if (photo && !broken) {
    return (
      <div style={{
        width: '100%', height: '100%', overflow: 'hidden',
        background: colors.bg, ...style
      }}>
        <img
          src={photo}
          alt={listing.name}
          onError={() => setBroken(true)}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
        />
      </div>
    );
  }

  return (
    <div style={{
      width: '100%', height: '100%', overflow: 'hidden',
      background: colors.bg, ...style
    }}>
      {PatternFn ? PatternFn(colors) : <div style={{width:'100%',height:'100%',background:colors.bg}}/>}
    </div>
  );
};

const CategoryBadge = ({ category, small = false }) => {
  const colors = CATEGORY_COLORS[category] || CATEGORY_COLORS["Pumpkin Patch"];
  return (
    <span style={{
      display: 'inline-block',
      background: colors.bg,
      color: colors.text,
      border: `1px solid ${colors.accent}40`,
      borderRadius: 4,
      padding: small ? '2px 8px' : '4px 10px',
      fontSize: small ? 11 : 12,
      fontFamily: 'DM Mono, monospace',
      fontWeight: 500,
      letterSpacing: '0.04em',
      textTransform: 'uppercase',
      whiteSpace: 'nowrap',
    }}>
      {category}
    </span>
  );
};

const StarRating = ({ rating, count, small = false }) => {
  if (rating == null) return null;
  const full = Math.floor(rating);
  const half = rating % 1 >= 0.5;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
      <div style={{ display: 'flex', gap: 1 }}>
        {[1,2,3,4,5].map(i => (
          <span key={i} style={{
            fontSize: small ? 11 : 13,
            color: i <= full ? '#C4922A' : (i === full+1 && half ? '#C4922A' : '#D4C8B0'),
            opacity: i === full+1 && half ? 0.6 : 1,
          }}>★</span>
        ))}
      </div>
      <span style={{
        fontSize: small ? 12 : 13,
        color: 'var(--bark-light)',
        fontFamily: 'DM Mono, monospace',
      }}>{rating.toFixed(1)}</span>
      {count && <span style={{
        fontSize: small ? 11 : 12,
        color: 'var(--bark-light)',
        fontFamily: 'Source Serif 4, serif',
      }}>({count})</span>}
    </div>
  );
};

const FarmCard = ({ listing, onClick, featured = false }) => {
  const [hovered, setHovered] = React.useState(false);
  const colors = CATEGORY_COLORS[listing.category] || CATEGORY_COLORS["Pumpkin Patch"];

  return (
    <div
      onClick={() => onClick(listing)}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        background: '#fff',
        borderRadius: 12,
        overflow: 'hidden',
        cursor: 'pointer',
        border: `1px solid ${hovered ? colors.accent + '40' : 'rgba(180,140,80,0.15)'}`,
        boxShadow: hovered
          ? `0 12px 40px rgba(0,0,0,0.12), 0 2px 8px rgba(0,0,0,0.06)`
          : `0 2px 12px rgba(0,0,0,0.05)`,
        transform: hovered ? 'translateY(-3px)' : 'none',
        transition: 'all 0.25s ease',
        position: 'relative',
      }}
    >
      {/* Image area */}
      <div style={{ height: 185, position: 'relative', overflow: 'hidden' }}>
        <FarmImage listing={listing} />
        {featured && (
          <div style={{
            position: 'absolute', top: 10, left: 10,
            background: 'var(--orange)', color: '#fff',
            padding: '3px 10px', borderRadius: 4,
            fontSize: 10, fontFamily: 'DM Mono, monospace',
            fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
            boxShadow: '0 2px 8px rgba(200,98,42,0.4)',
          }}>Featured</div>
        )}
        <div style={{
          position: 'absolute', top: 10, right: 10,
          background: 'rgba(253,246,236,0.92)',
          padding: '3px 8px', borderRadius: 4,
          fontSize: 11, fontFamily: 'DM Mono, monospace',
          color: 'var(--bark-light)',
        }}>{listing.distance} mi</div>
      </div>

      {/* Content */}
      <div style={{ padding: '14px 16px 16px' }}>
        <div style={{ marginBottom: 8 }}>
          <CategoryBadge category={listing.category} small />
        </div>
        <h3 style={{
          fontFamily: 'Playfair Display, serif',
          fontSize: 18, fontWeight: 700, lineHeight: 1.2,
          color: 'var(--bark)', marginBottom: 4,
        }}>{listing.name}</h3>
        <p style={{
          fontSize: 13, color: 'var(--bark-light)',
          fontFamily: 'DM Mono, monospace', marginBottom: 8,
          letterSpacing: '0.02em',
        }}>📍 {listing.city}, {listing.state}</p>
        <p style={{
          fontSize: 14, color: 'var(--bark-mid)',
          lineHeight: 1.5, marginBottom: 10,
          display: '-webkit-box',
          WebkitLineClamp: 2,
          WebkitBoxOrient: 'vertical',
          overflow: 'hidden',
        }}>{listing.shortDesc}</p>

        {/* Activity tags */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 12 }}>
          {listing.activities.slice(0, 3).map(act => (
            <span key={act} style={{
              fontSize: 11, color: 'var(--bark-light)',
              background: 'var(--cream-dark)',
              padding: '2px 7px', borderRadius: 3,
              fontFamily: 'Source Serif 4, serif',
            }}>{act}</span>
          ))}
          {listing.activities.length > 3 && (
            <span style={{
              fontSize: 11, color: 'var(--bark-light)',
              fontFamily: 'DM Mono, monospace',
            }}>+{listing.activities.length - 3}</span>
          )}
        </div>

        {/* Bottom row */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          paddingTop: 10, borderTop: '1px solid var(--cream-dark)',
        }}>
          {listing.rating != null
            ? <StarRating rating={listing.rating} count={listing.reviewCount} small />
            : <span style={{
                fontSize: 12, color: 'var(--bark-light)',
                fontFamily: 'DM Mono, monospace',
              }}>📍 {listing.distance} mi</span>}
          <span style={{
            fontSize: 12, color: 'var(--bark-light)',
            fontFamily: 'DM Mono, monospace',
          }}>
            {listing.season.slice(0,2).join(' · ')}
            {listing.season.length > 2 ? ' +' + (listing.season.length-2) : ''}
          </span>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  CATEGORY_COLORS, FarmImage, CategoryBadge, StarRating, FarmCard, CATEGORY_PATTERNS
});
